Prop-based Styling with Styled Components in React.js
About a month ago I introduced the concept of prop-based styling with React. It’s now time to combine both the power of the widely used styled-components library and PSS syntax.
The following example is quite common with styled-components:
- We’re creating a
button
tag - Some CSS properties are based on the component properties (
props.primary
,props.isSelected
) - Theming using
${props => props.theme.primary}
import styled from 'styled-components';export default styled.button`
background: ${props => props.primary ? 'palevioletred' : 'white'};
color: ${props => props.primary ? 'white' : 'palevioletred'};
border-radius: 3px; ${props => props.isSelected && css`
border: 2px solid;
border-color: ${props => props.theme.primary};
font-weight: bold;
`}
`;
Becomes,
button {
background: white;
color: palevioletred;
border-radius: 3px; &:primary {
background: palevioletred;
color: white;
}
&:isSelected {
border: 2px solid;
border-color: $theme.primary;
font-weight: bold;
}
}
The cool thing is that this syntax will generate JavaScript code during build time. With pss, you get a more readable, Sass-ish way of writing styles for your React components.
What it Does
Access your theme variables, the easy way:
background: $theme.primary; // ${props => props.theme.primary}
Same goes for any prop your component has:
color: $color; // ${props => props.color}
Use It Now
Thanks to a webpack loader, you can already adopt the PSS syntax.
yarn add pss-loader // or npm install pss-loader
It’s only a matter of a few lines inside your webpack.config.js
configuration file:
// Inside webpack.config.js
module: {
rules: [
{
test: /\.pss$/,
use: {
loader: 'pss-loader',
options: {
stylingLibrary: 'styled-components'
}
}
}
]
}
Now you’re ready to go. Create any .pss
file and import it inside your JavaScript file:
import React from 'react';
import ReactDOM from 'react-dom';
import Button from './Button.pss';ReactDOM.render(
<Button>Hello World</Button>,
document.getElementById('root')
);
So,
I’m really open to everyone’s thoughts. I only wish that this project could improve so it would benefit to the whole community.
Please let me know what you think about it. Any idea about the language itself or suggestions for other css-in-js librairies that should be added to the webpack loader.
I hope that you share the same enthusiasm than I do about this!
Thanks for reading and feel free to give a look at the repo! ⚡️
- Start using the Webpack loader
- PSS lang