Build styled component with css-modules
styled-component
forces developers use clearer way to add styles to the components which looks great to me, but there are still some difficult unsolved issues in CSS-in-JS area, even after radium
, aphrodite
and a lot of libraries involved.
css-modules
is a good choice for getting modularization without being as cutting-edge as the CSS-in-JS approaches. You can just write css and get full superpower from PostCSS ecosystem!
$ npm install styled-css-modules-component
Note: You have to setup your own css-modules environment.
styles.css
:
.title {
font-size: 1.5em;
text-align: center;
color: palevioletred;
}
.wrapper {
padding: 4em;
background: papayawhip;
}
This creates two react components, <Title>
and <Wrapper>
:
import React from 'react';
import styled from 'styled-css-module-components';
import styles from './styles.css';
// Create a <Title> react component that renders an <h1> which is
// centered, palevioletred and sized at 1.5em
const Title = styled.h1(styles.title);
// Create a <Wrapper> react component that renders a <section> with
// some padding and a papayawhip background
const Wrapper = styled.section(styles.wrapper);
You render them like so:
// Use them like any other React component – except they're styled!
<Wrapper>
<Title>Hello World, this is my first styled css modules component!</Title>
</Wrapper>
Checkout full examples here.
styles.css
:
.input {
font-size: 1.25em;
padding: 0.5em;
margin: 0.5em;
color: palevioletred;
background: papayawhip;
border: none;
border-radius: 3px;
}
Styled components pass on all their props. This is a styled <input>
:
import React from 'react';
import styled from 'styled-css-modules-components';
import styles from './styles.css';
// Create an <Input> component that'll render an <input> tag with some styles
const Input = styled.input(styles.input);
You can just pass a placeholder
prop into the styled-css-modules-component
. It will pass it on to the DOM node like any other react component:
// Render a styled input with a placeholder of "@chentsulin"
<Input placeholder="@chentsulin" type="text" />
Checkout full examples here.
styles.css
:
.link {
color: palevioletred;
display: block;
margin: 0.5em 0;
font-family: Helvetica, Arial, sans-serif;
}
The above also works perfectly for styling third-party components, like a react-router
<Link />
!
import styled from 'styled-css-modules-components';
import { Link } from 'react-router';
const StyledLink = styled(Link)(styles.link);
<Link to="/">Standard, unstyled Link</Link>
<StyledLink to="/">This Link is styled!</StyledLink>
Checkout full examples here.
Directly supported by CSS.
See the long discusses at css-modules #147.
Not supported.
MIT © C.T. Lin