How to Use Styled-Components in React

React JS

Learn how to use styled-components in React to create seamless and maintainable styles for your application. This guide covers the basics, setup, advanced features, and best practices.


NGNishan Giri
2024-06-13
How to Use Styled-Components in React

Styling is important for any web app. It helps create a good user experience. With React, we have new ways to add styles. One popular way is using styled-components. This blog will show you how to use styled-components in React. We'll cover the basics, some advanced features, and best practices.

Table of Contents


What are Styled-Components?

Styled-components is a library that helps you write CSS in your JavaScript files. It uses tagged template literals to style your components. This makes it easy to keep your styles scoped to specific components and adjust them based on props. This makes styling in React more modular and reusable.

Benefits of Using Styled-Components

Styled-components offer many benefits:

Setting Up Styled-Components in a React Project

To get started with styled-components:

  1. Install styled-components:
    npm install styled-components
    # or
    yarn add styled-components
  2. Create a new React app (if needed):
    npx create-react-app styled-components-demo
    cd styled-components-demo
  3. Import styled-components into your project:
    import styled from 'styled-components';

Basic Usage of Styled-Components

Creating Styled Components

Here’s an example of a styled button component:

const Button = styled.button`
  background-color: #007bff;
  color: white;
  border: none;
  padding: 10px 20px;
  border-radius: 4px;
  cursor: pointer;
 
  &:hover {
    background-color: #0056b3;
  }
`;

Use this component like any other React component:

import React from 'react';
 
function App() {
  return (
    <div>
      <h1>Welcome to Styled-Components!</h1>
      <Button>Click me</Button>
    </div>
  );
}
 
export default App;

Props and Dynamic Styles

You can pass props to dynamically adjust styles:

const Button = styled.button`
  background-color: ${props => props.primary ? '#007bff' : 'white'};
  color: ${props => props.primary ? 'white' : 'black'};
  border: ${props => props.primary ? 'none' : '2px solid #007bff'};
`;
 
function App() {
  return (
    <div>
      <Button primary>Primary Button</Button>
      <Button>Secondary Button</Button>
    </div>
  );
}

Advanced Features

Theming

Styled-components make it easy to apply themes:

const theme = {
  primaryColor: '#007bff',
  secondaryColor: '#6c757d',
};
 
const Button = styled.button`
  background-color: ${props => props.primary ? props.theme.primaryColor : props.theme.secondaryColor};
  color: white;
  border: none;
  padding: 10px 20px;
  border-radius: 4px;
`;
 
import { ThemeProvider } from 'styled-components';
 
function App() {
  return (
    <ThemeProvider theme={theme}>
      <Button primary>Primary Button</Button>
      <Button>Secondary Button</Button>
    </ThemeProvider>
  );
}

Global Styles

Define global styles using createGlobalStyle:

import { createGlobalStyle } from 'styled-components';
 
const GlobalStyle = createGlobalStyle`
  body {
    font-family: 'Arial', sans-serif;
    margin: 0;
    padding: 0;
    box-sizing: border-box;
  }
`;
 
function App() {
  return (
    <ThemeProvider theme={theme}>
      <GlobalStyle />
      <Button primary>Primary Button</Button>
      <Button>Secondary Button</Button>
    </ThemeProvider>
  );
}

Extending Styles

Extend existing styles easily:

const Button = styled.button`
  background-color: #007bff;
  color: white;
  border: none;
  padding: 10px 20px;
  border-radius: 4px;
`;
 
const PrimaryButton = styled(Button)`
  background-color: #0056b3;
`;

Animations

Create and use animations with styled-components:

import styled, { keyframes } from 'styled-components';
 
const slideIn = keyframes`
  from {
    opacity: 0;
  }
  to {
    opacity: 1;
  }
`;
 
const Toast = styled.div`
  animation: ${slideIn} 0.5s ease-in-out;
  border-radius: 5px;
  padding: 20px;
  position: fixed;
  top: 20px;
  right: 20px;
  background-color: #007bff;
  color: white;
`;
 
function App() {
  return <Toast>Slide in animation!</Toast>;
}

Polymorphic Components

The "as" prop changes the rendered HTML element:

const StyledContainer = styled.section`
  max-width: 1024px;
  margin: 0 auto;
`;
 
function App() {
  return (
    <StyledContainer as="div">
      <h1>Rendered as a div</h1>
    </StyledContainer>
  );
}

Best Practices for Using Styled-Components

Common Pitfalls and How to Avoid Them

Conclusion

Styled-components offer a powerful and flexible way to style React components. With scoped and dynamic styles, theming support, and advanced features like animations and polymorphic components, styled-components enhance the development experience and improve code maintainability. Whether you're building a simple website or a complex application, styled-components can streamline your styling process.

Happy Coding! 😊