Styled-components allows us to create a normal React component that has styles bound to it. There are many benefits to implementing styled-components in your React app:
- CSS becomes easier to maintain and update when you no longer have to search through multiple files and folders to find the styling for a particular element.
- Allows for dynamic rendering of elements based on a component’s props.
- It makes removing CSS easier because you don’t have to worry about other elements using the same
- Styled-components keeps track of which components are rendered on a page and injects their styles and nothing else, fully automatically.
You only need one line in your terminal to get things up and running! To install styled-components with npm, simply run:
Or, if you’re using a package manager like yarn:
The docs also highly recommend adding styled-components to the ‘resolutions’ field in your package.json if you’re using yarn.
Once you’ve got everything installed, it’s time to get to styling. Here we’re creating a component,
Title, that will render a styled <h1> element.
** Don’t forget to
import styled from 'styled-components' at the top of your component!
Easy, right? With styled-components we can style any html element: divs, sections, buttons, anything! Styled-components gets even more fun and interesting to use when an element’s style changes based on its props.
Another great thing about styled-components is the ability to extend one component’s style to another. Here we have a styled div
Block whose CSS is extended to
RedBlock with one small change.
So there you have it! A beginner’s guide to React styled-components!