• Stars
    star
    1,362
  • Rank 33,224 (Top 0.7 %)
  • Language
    JavaScript
  • License
    MIT License
  • Created about 7 years ago
  • Updated over 1 year ago

Reviews

There are no reviews yet. Be the first to send feedback to the community and the maintainers!

Repository Details

Visual primitives for the component age. A simple port for Vue of styled-components πŸ’…

vue-styled-components

Visual primitives for the component age. Use the best bits of ES6 and CSS to style your apps without stress πŸ’…

Support

This version is compatible with Vue 2.x

yarn add vue-styled-components

Utilising tagged template literals (a recent addition to JavaScript) and the power of CSS allows you to write actual CSS code to style your components. It also removes the mapping between components and styles – using components as a low-level styling construct could not be easier!

This is a (not fully-featured)fork from original styled-components made by Glen Maddern and Max Stoiber, supported by Front End Center and Thinkmill. Thank you for making this project possible!

Usage

Register first your component locally (see https://vuejs.org/v2/guide/components.html#Local-Registration)

  new Vue({
    // ...
    components {
      'styled-title': StyledTitle
    },
    template: '<styled-title> Hello! </styled-title>'
  }

Basic

Do not use built-in or reserved HTML elements as component id (title, button, input...).

This creates two Vue components, <StyledTitle> and <Wrapper>:

import styled from 'vue-styled-components';

// Create a <StyledTitle> Vue component that renders an <h1> which is
// centered, palevioletred and sized at 1.5em
const StyledTitle = styled.h1`
  font-size: 1.5em;
  text-align: center;
  color: palevioletred;
`;

// Create a <Wrapper> Vue component that renders a <section> with
// some padding and a papayawhip background
const Wrapper = styled.section`
  padding: 4em;
  background: papayawhip;
`;

You render them like so:

// Use them like any other Vue component – except they're styled!
<wrapper>
  <styled-title>Hello World, this is my first styled component!</styled-title>
</wrapper>

Passed props

Styled components pass on all their props. This is a styled <input>:

import styled from 'vue-styled-components';

// Create an <StyledInput> component that'll render an <input> tag with some styles
const StyledInput = styled.input`
  font-size: 1.25em;
  padding: 0.5em;
  margin: 0.5em;
  color: palevioletred;
  background: papayawhip;
  border: none;
  border-radius: 3px;

  &:hover {
    box-shadow: inset 1px 1px 2px rgba(0,0,0,0.1);
  }
`;

You can just pass a placeholder prop into the styled-component. It will pass it on to the DOM node like any other Vue component:

// Render a styled input with a placeholder of "@liqueflies"
<styled-input placeholder="@liqueflies" type="text" />

Adapting based on props

This is a button component that has a primary state. By setting primary to true when rendering it we adjust the background and text color.

Important

A prop is a custom attribute for passing information from parent components. A child component needs to explicitly declare the props it expects to receive using the props option, you must define your prop before, and of course, get benefits of validation! (see https://vuejs.org/v2/guide/components.html#Passing-Data-with-Props)

{
  props: {
    propA: String,
    propB: [String, Number]
  }
}
import styled from 'vue-styled-components';

const btnProps = { primary: Boolean };

const StyledButton = styled('button', btnProps)`
  font-size: 1em;
  margin: 1em;
  padding: 0.25em 1em;
  border: 2px solid palevioletred;
  border-radius: 3px;
  background: ${props => props.primary ? 'palevioletred' : 'white'};
  color: ${props => props.primary ? 'white' : 'palevioletred'};
`;

export default StyledButton;
<styled-button>Normal</styled-button>
<styled-button primary>Primary</styled-button>

Overriding component styles

Taking the StyledButton component from above and removing the primary rules, this is what we're left with – just a normal button:

import styled from 'vue-styled-components';

const StyledButton = styled.button`
  background: white;
  color: palevioletred;
  font-size: 1em;
  margin: 1em;
  padding: 0.25em 1em;
  border: 2px solid palevioletred;
  border-radius: 3px;
`;

export default StyledButton;

Theming

vue-styled-components has full theming support by exporting a <ThemeProvider> wrapper component. This component provides a theme to all Vue components underneath itself via the context API. In the render tree all vue-styled-components will have access to the provided theme, even when they are multiple levels deep.

Remember to register ThemeProvider locally.

  import {ThemeProvider} from 'vue-styled-components'

  new Vue({
    // ...
    components: {
      'theme-provider': ThemeProvider
    },
    // ...
  });

Add your ThemeProvider component:

  <theme-provider :theme="{
    primary: 'palevioletred'
  }">
    <wrapper>
      // ...
    </wrapper>
  </theme-provider>

And into your Wrapper component:

  const Wrapper = styled.default.section`
    padding: 4em;
    background: ${props => props.theme.primary};
  `;

Style component constructors as router-link

You can style also Vue component constructors as router-link from vue-router and other components

import styled from 'vue-styled-components';

// unfortunately you can't import directly router-link, you have to retrieve contstructor
const RouterLink = Vue.component('router-link')

const StyledLink = styled(RouterLink)`
  color: palevioletred;
  font-size: 1em;
  text-decoration: none;
`;

export default StyledLink;
<styled-link to="/">Custom Router Link</styled-link>

Let's say someplace else you want to use your button component, but just in this one case you want the color and border color to be tomato instead of palevioletred. Now you could pass in an interpolated function and change them based on some props, but that's quite a lot of effort for overriding the styles once.

To do this in an easier way you can call StyledComponent.extend as a function and pass in the extended style. It overrides duplicate styles from the initial component and keeps the others around:

// Tomatobutton.js

import StyledButton from './StyledButton';

const TomatoButton = StyledButton.extend`
  color: tomato;
  border-color: tomato;
`;

export default TomatoButton;

Polymorphic as prop

If you want to keep all the styling you've applied to a component but just switch out what's being ultimately rendered (be it a different HTML tag or a different custom component), you can use the "as" prop to do this at runtime. Another powerful feature of the as prop is that it preserves styles if the lowest-wrapped component is a StyledComponent.

Example In Component.js

//  Renders a div element by default.
const Component = styled('div', {})``

Using the as prop in another template/component would be as shown below.

<template>
  <!-- Component will render a button instead of a div -->
  <Component as="button" color="red">
    Button
  </Component>
</template>

This sort of thing is very useful in use cases like a navigation bar where some of the items should be links and some just buttons, but all be styled the same way.

withComponent

Let's say you have a button and an a tag. You want them to share the exact same style. This is achievable with .withComponent.

const Button = styled.button`
  background: green;
  color: white;
`
const Link = Button.withComponent('a')

injectGlobal

A helper method to write global CSS. Does not return a component, adds the styles to the stylesheet directly.

We do not encourage the use of this. Use once per app at most, contained in a single file. This is an escape hatch. Only use it for the rare @font-face definition or body styling.

// global-styles.js

import { injectGlobal } from 'vue-styled-components';

injectGlobal`
	@font-face {
	  font-family: 'Operator Mono';
	  src: url('../fonts/Operator-Mono.ttf');
	}

	body {
		margin: 0;
	}
`;

Syntax highlighting

The one thing you lose when writing CSS in template literals is syntax highlighting. We're working hard on making proper syntax highlighting happening in all editors. We currently have support for Atom, Visual Studio Code, and soon Sublime Text.

Atom

@gandm, the creator of language-babel, has added support for styled-components in Atom!

To get proper syntax highlighting, all you have to do is install and use the language-babel package for your JavaScript files!

Sublime Text

There is an open PR by @garetmckinley to add support for styled-components to babel-sublime! (if you want the PR to land, feel free to πŸ‘ the initial comment to let the maintainers know there's a need for this!)

As soon as that PR is merged and a new version released, all you'll have to do is install and use babel-sublime to highlight your JavaScript files!

Visual Studio Code

The vscode-styled-components extension provides syntax highlighting inside your Javascript files. You can install it as usual from the Marketplace.

VIM / NeoVim

The vim-styled-components plugin gives you syntax highlighting inside your Javascript files. Install it with your usual plugin manager like Plug, Vundle, Pathogen, etc.

Also if you're looking for an awesome javascript syntax package you can never go wrong with YAJS.vim.

Other Editors

We could use your help to get syntax highlighting support to other editors! If you want to start working on syntax highlighting for your editor, open an issue to let us know.

License

Licensed under the MIT License, Copyright Β© 2017 Lorenzo Girardi.

See LICENSE for more information.

More Repositories

1

styled-components

Visual primitives for the component age. Use the best bits of ES6 and CSS to style your apps without stress πŸ’…
TypeScript
39,930
star
2

polished

A lightweight toolset for writing styles in JavaScript ✨
JavaScript
7,562
star
3

awesome-styled-components

A curated list of awesome styled-components resources πŸ’…
3,283
star
4

xstyled

A utility-first CSS-in-JS framework built for React. πŸ’…πŸ‘©β€πŸŽ€βš‘οΈ
MDX
2,254
star
5

jest-styled-components

πŸ”§ πŸ’… Jest utilities for Styled Components
JavaScript
1,577
star
6

styled-theming

Create themes for your app using styled-components
JavaScript
1,168
star
7

css-to-react-native

Convert CSS text to a React Native stylesheet object
JavaScript
1,117
star
8

babel-plugin-styled-components

Improve the debugging experience and add server-side rendering support to styled-components
JavaScript
1,063
star
9

vscode-styled-components

Syntax highlighting for styled-components
JavaScript
911
star
10

stylelint-processor-styled-components

Lint your styled components with stylelint!
JavaScript
657
star
11

styled-components-website

The styled-components website and documentation
MDX
607
star
12

webstorm-styled-components

styled-components highlighting support in IntelliJ editors
Kotlin
377
star
13

vim-styled-components

Vim bundle for http://styled-components.com based javascript files.
Vim Script
300
star
14

comparison

Comparing different ways to style components
JavaScript
183
star
15

elm-styled

Styling your Html Elements with typed Css πŸ’…
Elm
180
star
16

babel-plugin-polished

Compile polished helper functions at build time
JavaScript
138
star
17

styled-elements

Styled components for the DOM.
JavaScript
87
star
18

stylelint-config-styled-components

The shareable stylelint config for stylelint-processor-styled-components
JavaScript
71
star
19

spec

Design Requirements and Spec for a Component-oriented CSS Solution
61
star
20

color-schemer

A React app to help you select a color scheme, built with styled-components and polished
JavaScript
55
star
21

styled-components-codemods

Automatic codemods to upgrade your styled-components code to newer versions.
JavaScript
52
star
22

styled-components-experimentation

A place to play with things that shouldn't be in core
JavaScript
31
star
23

s-c.sh

The styled-components URL shortener!
30
star
24

styled-components-native-code-mod

JavaScript
28
star
25

styled-components.github.io

The styled-components homepage
JavaScript
22
star
26

brand

Logo and brand related materials
11
star
27

benchmark

JavaScript
9
star
28

todomvc

The Speedometer 2.0 React TodoMVC example rebuilt with styled-components
JavaScript
6
star
29

babel-plugin-styled-components-ssr

[EXPERIMENTAL]
JavaScript
2
star
30

use-styled-hook

tbd
1
star