DEV Community

Cover image for How to use CSS in Media Queries with styled components in React js
Sudhanshu Gaikwad
Sudhanshu Gaikwad

Posted on

How to use CSS in Media Queries with styled components in React js

Step 1: Install Styled Components
First, make sure you have styled-components installed in your project. If not, you can install it using npm or yarn:

npm install styled-components
Enter fullscreen mode Exit fullscreen mode

Step 2: Create a Styled Component with Media Queries
You can create a styled component and use media queries within it. Here’s an example of a responsive Container component that changes its background color based on the screen width:

import React from 'react';
import styled from 'styled-components';

// Define the styled component with media queries
const Container = styled.div`
  width: 100%;
  height: 100vh;
  background-color: lightblue;

  @media (max-width: 768px) {
    background-color: lightcoral;
  }

  @media (max-width: 480px) {
    background-color: lightgreen;
  }
`;

const App = () => {
  return (
    <Container>
      <h1>Hello, World!</h1>
    </Container>
  );
};

export default App;
Enter fullscreen mode Exit fullscreen mode

Explanation
Import Styled Components: Import the styled object from styled-components.
Create a Styled Component: Define a styled Container component. The Container will have a default background color of lightblue.
Add Media Queries:
For screens with a maximum width of 768px, change the background color to lightcoral.
For screens with a maximum width of 480px, change the background color to lightgreen.
Use the Styled Component: Use the Container component in your App component. Any content inside the Container will have the styles applied to it, including the media queries.

Step 3: Render the App
When you run your React application, you should see the Container change its background color based on the screen width:

Default: lightblue
Max-width 768px: lightcoral
Max-width 480px: lightgreen

This way, you can easily add responsive styles to your React components using CSS Media Queries with Styled Components.

Additional Tips
You can add more complex styles and media queries as needed.
Combining media queries with other styled-component features (e.g., themes) can make your styles even more powerful and maintainable.

Top comments (2)

Collapse
 
jgdevelopments profile image
Julian Gaston

Hey, good read!
One quick thing I wanted to mention, it appears your code blocks are not highlighted. There is a great article that goes over this. Highly recommend.
dev.to/hoverbaum/how-to-add-code-h...

Collapse
 
sudhanshu_developer profile image
Sudhanshu Gaikwad • Edited

okay, I will highlight my code. Thank you for recommending me.