Introduction To Styled-Components
Introduction
You are living in interesting times, especially if you are a Frontend Developer. There are plenty of methodologies which you can use for styling your application such as React development. This JavaScript library added its block to support the CSS-in-JS approach by default. This started an interesting battle for the best CSS-in-JS library and one of the most popular solutions is styled-components, which I would like to briefly introduce below.
CSS-in-JS is not a wholly agreed-upon approach for those developers who are use used to the “traditional” separation of CSS from HTML tags and who have heard thousands of times that it is bad practice of mixing those two technologies together. However, nowadays it is becoming more and more popular.The main reason for this popularity is really simple: finally, we can use the power of JavaScript inside our stylesheets.
The easiest way we can modify styles with JavaScript is by using inline styles. It is not super efficient and even elegant, but it is absolutely legal and the greatest benefit of that technique is the styles will be encapsulated in the scope of the component. No more global style pollution! React supports inline styles from the beginning of its existence so it can be a way of creating styles in React applications. But is it the best choice? Of course not! Fortunately, we have some other options. There are a lot of libraries which support the CSS-in-JS approach but I would like to focus on the currently most popular, which is styled-components.
Check out how we do this at Pagepro, an experienced React Development Company.
READY TO START YOUR NEW PROJECT?
Getting hands dirty with a small example
It will be easier to understand what styled-components are with a simple example of a button. Let’s start with the installation process. I will use Yarn package manager to do that and I just have to run the command below in my terminal:
yarn add styled-components
Forget about external tools at the moment, just focus on creating the first component. Somewhere in your React code put these simple lines:
import styled from 'styled-components';
const StyledButton = styled.button`
background-color: red;
`;
Looks pretty nice, doesn’t it? First of all, we have to import styled function from styled-components package and after that, we can choose from the predefined set of HTML tags (the library supports them all) an interesting component to use. The part of the code on the right side looks like function invocation but instead of brackets we have backticks. And definitely this is true because styled-components uses one of the newest feature from ES6 standard of JavaScript called tagged template literals. You can read more about it here. So basically the code between backticks is a body of the button function. Looks familiar? Well, it should, because this is a regular CSS code with regular CSS syntax. It is quite important because many of CSS-in-JS libraries use camelCase syntax (similar to JS objects) and it can be a source of mistakes to replace all well-known rule names with camel case equivalents.
To make this component visible on the page you have to use it as a normal React component:
<StyledButton>Click me!</StyledButton>
Just make sure you have this part somewhere in your render()
method. And that is all! Incredibly easy to start with if you know CSS. But I will show you something more powerful than CSS!
Use force Luke! I meant JavaScript of course!
Imagine that you want to create a half transparent button in case someone doesn’t fill all inputs in a form. Then, you can pass additional properties into a styled component in the same way you pass them in other React components:
const StyledButton = styled.button`
background-color: red;
opacity: $(props => (props.disabled ? '.5' : '1'));
`;
This looks more dynamic. If you pass a disabled prop
, our button will be half transparent:
<StyledButton disabled>Click me!</StyledButton>
The props
object is always available in the scope of the styled-components function so you don’t have to worry about how to pass it manually. This is a really simple example and sometimes we need to add more styles when the state of our application changes. There is an elegant solution to do that:
const DisabledButton = styled(StyledButton)`
background-color: black;
color: white;
pointer-events: none;
opacity: '.5';
`;
This time I wrapped our old StyledButton with a styled function and it returns a new button with some extra styles. In this particular case of using the styled function we can achieve inheritance in our components. Base styles belong to StyledButton and we can override them (or add new) by “extending” this component with styled()
invocation on the StyledButton. Now you can use the new button in your code like this:
<DisabledButton>You cannot click me!<DisabledButton>
What else can I do?
The examples which I presented are really simple, but styled-components has more useful features including:
- Nested rules – if you are familiar with SASS or LESS preprocessor you know how nesting rules can be useful. With styled-components it is possible too
- Vendor prefixing – forget about adding extra prefixes for specific browsers. This step is done for you automatically
- Scoped selectors – you don’t have to think about naming conventions or methodologies like BEM to avoid selector collisions on your pages
- Dead code elimination – styled-components has an optional configuration to remove code which does not affect the program results
- Stylelint support – good real-time linting is priceless when you have to debug your styles
- React Native support – this is a huge feature! React Native supports only camelCase syntax by default but you can safely use styled-components to style native controls
- Theming – styled-components uses similar approach to new React context api for theming. Switching between different templates can be really easy!
- Server side rendering support – by using
ServerStyleSheet
object andStyleSheetManager
you can utilize all styles from the client side and returns them from the server side - Code minification – your application will be smaller and what is important – this feature is enabled by default!
- Plugin for Jest test framework – an absolutely necessary thing for snapshot testing
- Plugins for popular editors – coding styles without syntax highlighting can be a pain in the neck but fortunately there are appropriate plugins for editors like VS Code, Sublime Text or Vim
As you can see, there are lot of features which you can use while working with styled-components.
Summary
Styled-components is a fantastic library for creating maintainable, reusable, scoped (ahhh so many advantages!) styles for React applications. It’s super easy to use and you don’t have to learn new syntax or commands. If you like additional features like nesting rules or mixins which come with preprocessors, you can use these features in styled-components too!
Of course, the idea behind styled-components can be really weird at the beginning of your journey but if you give it a try, you will love it.
comments
Comments are closed.