Styled Components
What is it?
styled-components is a library that helps creating React components from HTML elements with associated CSS styles in a simple and straightforward syntax. To do that, it allows to write actual CSS queries in our JavaScript files.
How to use it
To install the library, simply run:
npm install --save styled-components
After this, you can import the library in your code and start using it.
import styled from 'styled-components'
Syntax
The syntax used in styled-components seems weird at first, but it's quite simple. It uses these backticks to surround the rules you are writing, which are tagged template literals (don't worry much about it, just remember to use the backticks when creating a new component).
We recommend using some syntax highlighter to help. You can find the one that suits your IDE and personal taste in the official documentation. styled-components: Tooling
Simple Example
Take a look at this simple example taken from the official documentation:
import styled, { css } from 'styled-components';
const Button = styled.button`
background: transparent;
border-radius: 3px;
border: 2px solid palevioletred;
color: palevioletred;
margin: 0.5em 1em;
padding: 0.25em 1em;
${(props) =>
props.primary &&
css`
background: palevioletred;
color: white;
`}
`;
const Container = styled.div`
text-align: center;
`;
render(
<Container>
<Button>Normal Button</Button>
<Button primary>Primary Button</Button>
</Container>
);
In the first line we are importing the library styled and { css }.
In the next line, we create a new component Button that will render an HTML button with the CSS styles informed.
The { css } import is used to allow the dynamic control of new CSS rules with properties passed to the styled component.
Common practices
Here are some common practices used during development:
import styled, { css } from 'styled-components';
/*We can import pre-made components and edit them with the following syntax*/
import { Layout, Button } from 'antd';
const StyledLayout = styled(Layout)`
height: auto;
min-height: 100vh;
`;
/* We can also directly edit CSS classes for a given component*/
export const ButtonStyled = styled(Button)`
font-weight: 700 !important;
&.secondary {
background-color: 'red';
border-color: 'red';
color: white;
}
&.outlined {
background-color: transparent;
color: 'blue' !important;
border-color: 'blue' !important;
}
`;
render(
<StyledLayout>
<ButtonStyled class='secondary'>Secondary Button</ButtonStyled>
<ButtonStyled class='outlined'>Outlined Button</ButtonStyled>
</StyledLayout>
);
Learn More
styled-components: Documentation
Styled Components: To Use or Not to Use?
Practice
Create and render simple components with the library. For example:
- A Button that changes the background color with props (styled.button
...
) - A Container that centers the elements rendered inside it (styled.div
...
) - Import an element from a library (Antd or MaterialUI) and create a Styled Component from it