Skip to Content
šŸ‘† We offer 1-on-1 classes as well check now
React.jsStylingStyled Components

Styled Components

Styled components are a popular way to style React applications, allowing you to write CSS code within your JavaScript files. This approach provides a more modular and reusable way of styling your components. With React 19, styled components have become even more powerful, integrating seamlessly with modern React features.

Basic Example

To get started with styled components, you first need to install the styled-components library. You can do this by running npm install styled-components or yarn add styled-components in your project directory. Here’s a simple example of how to use styled components:

import styled from 'styled-components'; const Button = styled.button` background-color: #4CAF50; color: #fff; padding: 10px 20px; border: none; border-radius: 5px; cursor: pointer; `; function MyComponent() { return ( <div> <Button>Click me</Button> </div> ); }

In this example, we define a Button component using the styled.button method, and then use it in our MyComponent function. The CSS styles are defined within the backticks, allowing us to use CSS syntax directly in our JavaScript file.

Advanced Usage

For more complex styling, you can use props to make your styled components more dynamic. Here’s an example:

import styled from 'styled-components'; const Button = styled.button` background-color: ${(props) => props.primary ? '#4CAF50' : '#fff'}; color: ${(props) => props.primary ? '#fff' : '#4CAF50'}; padding: 10px 20px; border: none; border-radius: 5px; cursor: pointer; `; function MyComponent() { return ( <div> <Button primary>Primary Button</Button> <Button>Secondary Button</Button> </div> ); }

In this example, we’ve added a primary prop to our Button component, which changes the background and text colors based on the prop value.

Best Practices

When using styled components, keep the following best practices in mind:

  • Keep your styled components modular and reusable.
  • Use props to make your styled components more dynamic.
  • Avoid using !important in your CSS styles, as it can lead to harder-to-debug code.
  • Use a consistent naming convention for your styled components.

Key Takeaways

  • Use styled components to write CSS code within your JavaScript files.
  • Make your styled components modular and reusable.
  • Use props to add dynamic styling to your components.
  • Follow best practices to keep your code clean and maintainable.
Last updated on