Logo

Developer learning path

React

Styled Components in React

Styled Components

35

#description

Styled components is a popular CSS-in-JS library that allows you to write CSS code directly in your JavaScript code. It provides a new way of styling React components that is more maintainable and allows for easier reuse of styling code.

With styled components, you can define styles for your components using a similar syntax to regular CSS.

For example, you can define styles for a button component like this:

                    
import styled from 'styled-components';

const Button = styled.button`
  background-color: blue;
  color: white;
  border-radius: 4px;
  padding: 8px 16px;
`;
                  

Here, we are defining a new button component using the styled.button syntax. We then define the styles for this button using the backtick notation (template literals) to enclose our CSS rules in a JavaScript template literal.

With styled components, you can also dynamically change styles based on props or global theme variables.

For example:

                    
import styled from 'styled-components';

const Button = styled.button`
  background-color: ${props => props.disabled ? 'grey' : 'blue'};
  color: ${props => props.disabled ? 'white' : 'black'};
  border-radius: 4px;
  padding: 8px 16px;
`;
                  

Here, we're defining styles for a button component that change depending on whether it's disabled or not. We use the props object to conditionally change the background-color and color properties.

Overall, styled components provide a powerful and flexible way to style your React components that can make your code more maintainable and reusable.

March 25, 2023

If you don't quite understand a paragraph in the lecture, just click on it and you can ask questions about it.

If you don't understand the whole question, click on the buttons below to get a new version of the explanation, practical examples, or to critique the question itself.