In this article, we will take a look at how to use styled-components in a React application.
By the end of the article, you should have an understanding of how to do the following:
Create a styled component
Pass props to a styled component
Create and use a theme
Before we dive into the code, let’s first do a quick overview of the styled-components library and understand the benefits of using it.
What Is Styled-Components?
There are many options you can take when it comes to styling a React application. The traditional way would be to create an external CSS file, then pass the attributes as a string on the className prop.
“Use the best bits of ES6 and CSS to style your apps without stress.” — styled-components website
Benefits of using styled-components
Automatic critical CSS — styled-components keeps track of which components are rendered on a page and only adds their styles
No class name bugs — styled-components generates a unique class name for the styles
Easier deletion of CSS — styles are tied to a specific component rather than being added as a class name
Simple dynamic styling — styles can be added to a component based on props or a theme
Painless maintenance — styles added to a component is done all in one place, rather than across multiple files
Automatic vendor prefixing — styled-components handles all of this
Create a Styled Component
To get started, let’s create our first styled component. I will be working on a basic create-react-app project with TypeScript support. You can follow along with or without TypeScript.
The conventional way to name a file when using styled-components is componentName.styled.ts. Where “componentName” is replaced with the name of the component.
For example, I will create a new file called /src/components/styles/Button.styled.ts. This is where I will create my component.
In this file, first import styled from 'styled-components';. Then, you can use styled to create a styled component.
“Styled components utilises tagged template literals to style your components.” — styled-components website
In other words, when you are defining styles, you are actually creating a component that has the styles attached to it using template literals.
First, type styled. followed by a valid React component or a tagname like ‘div’. For this example, we will create a styled button component.
export const Button = styled.button
padding: 0.5rem 1rem;
We can now use this Button component like any normal element in our app.
When we render the button, it will now have all of the styles with it.