Styled Components in React
Styled Components
35
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