Styled-Components

Styled-components Examples on CodeSandbox

Using styled-components with react

First you need to install styled-components. In your terminal, type yarn add styled-components. If you are using CodeSandbox, go to "Add Dependency", find styled-components and it will be installed.

As you can see in the above examples, we're using styled-components by first importing it. Then, we can use the styled method, followed by the element we want to style, styled.div, and then add backticks to denote our template which we can add regular CSS syntax into. As you can see below, there's a lot going on in here.

import styled from 'styled-components';
const Block = styled.div`
background-color: white;
color: ${({ color }) => color || "blue"};
padding: 10px;
border: 1px solid ${({ color }) => color || "blue"};
display: inline-block;
margin: 5px;
cursor: pointer;
&:hover {
background-color: lightblue;
}
`;

Access React props from Styled-components

As you can see in the above example, we created this component called Block which is just a rectangle. In there, we add this line: color: ${({ color }) => color || "blue"};. This can be quite confusing even to those experienced with React. What's going on here is we're actually destructuring off of the React props. This is the same as saying: color: ${props => props.color || "blue"}; Still confused? This still might look weird as we didn't explain what the arrow function actually does. Well, this is just a callback function provided by styled-components. It's actually the same as defining a regular JavaScript function:

color: ${function(props){
if(props.color){
return props.color;
}
return "blue";
}}

The one lined statement we defined originally is just the above JavaScript simplified with ES6 shorthand: arrow functions & object destructuring. So anyway, this allows you to dynamically set style attributes of this component: <Block color="green">Ex B</Block>. This creates a Block with green text.

Styled-components hover selector

You can utilize the CSS hover selector easily within a styled-component.

const Block = styled.div`
background-color: white;
&:hover {
background-color: lightblue;
}
`;

When hovering on this element, see the background-color change.

🛈 React School creates templates and video courses for building beautiful apps with React. Download our free Material UI template.