Styling React Using CSS 6 Methods

RMAG news

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

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;

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.