Tips on organizing media queries for multiple components styled in React

Struggling to avoid repeating media queries for all styled components? Have a grid layout that needs rearranging when the display screen changes? It can be tedious reusing the same media query for each styled component.

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

const Container = styled.div`
    height: 100%;
    display: grid;
    grid-template-columns: repeat(12, 1fr);
    grid-template-rows: 60% 40%;

    @media screen and (max-width: 768px) {
        grid-template-columns: 1fr;
        grid-template-rows: 30% 20% 30% 30%;
    }
`
const MainContainer = styled.div`
    background-color: salmon;
    grid-column: span 8;

    @media screen and (max-width: 768px) {
        grid-column: span 12;
    }
`
const ListContainer = styled.div`
    background-color: violet;
    grid-column: span 4;
    grid-row: span 2;

    @media screen and (max-width: 768px) {
        grid-column: span 12;
        grid-row: 2;
    }
    
`
const Item2 = styled.div`
    background-color: fuchsia;
    grid-column: span 3;

    @media screen and (max-width: 768px) {
        grid-column: span 12;
        grid-row: 3;
    }
`
const Item3 = styled.div`
    background-color: lawngreen;
    grid-column: span 5;

    @media screen and (max-width: 768px) {
        grid-column: span 12;
        grid-row: 4;
    }
`


const Home = () => {

    return(
        <Container>
            <MainContainer>Main</MainContainer>
            <ListContainer>List</ListContainer>
            <Item2>Today</Item2>
            <Item3>Forecast</Item3>
        </Container>
    )
}

export default Home

Looking to streamline your code by using media queries just once across all styled components?

@media screen and (max-width: 768px) {
     MainContainer {
         /*some changes style*/
     }
     Item2{
         /*some other changes style*/
     }
     /* ....and so on */
}

How can you achieve this with styled components without repetitive code for each component?

Have you tried applying the same media query to each styled component but looking for a more efficient solution?

****Edit With inspiration from @Pius Kariuki, I have found a solution:

    const MainContainer = styled.div`
    background-color: salmon;
    grid-column: span 8;
`
const ListContainer = styled.div`
    background-color: violet;
    grid-column: span 4;
    grid-row: span 2;
`
const Item2 = styled.div`
    background-color: fuchsia;
    grid-column: span 3;

`
const Item3 = styled.div`
    background-color: lawngreen;
    grid-column: span 5;
`
const Container = styled.div`
    height: 100%;
    display: grid;
    grid-template-columns: repeat(12, 1fr);
    grid-template-rows: 60% 40%;

    @media screen and (max-width: 768px) {
        grid-template-columns: 1fr;
        grid-template-rows: 30% 20% 30% 30%;
        
        ${Item3} {
            grid-column: span 12;
            grid-row: 4;          
        }
        ${Item2} {
            grid-column: span 12;
            grid-row: 3;
        }
        ${ListContainer} {
            grid-column: span 12;
            grid-row: 2;
        }
        ${MainContainer} {
            grid-column: span 12;
        }
    }
`

Make sure to define the styles for Container at the end after all child elements are declared.

Answer №1

To prevent redundancy by repeating the media query in all styled components, you can utilize the CSS @media rule to specify the adjustments for each component within it. See below for a practical illustration:

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

const Container = styled.div`
    height: 100%;
    display: grid;
    grid-template-columns: repeat(12, 1fr);
    grid-template-rows: 60% 40%;

    /* Media Query */
    @media screen and (max-width: 768px) {
        grid-template-columns: 1fr;
        grid-template-rows: 30% 20% 30% 30%;
    }
`
const MainContainer = styled.div`
    background-color: salmon;
    grid-column: span 8;
`
const ListContainer = styled.div`
    background-color: violet;
    grid-column: span 4;
    grid-row: span 2;
`
const Item2 = styled.div`
    background-color: fuchsia;
    grid-column: span 3;
`
const Item3 = styled.div`
    background-color: lawngreen;
    grid-column: span 5;
`

/* Global Media Query for all components */
@media screen and (max-width: 768px) {
     ${MainContainer} {
         /* Define changes for MainContainer here */
     }
     ${Item2} {
         /* Specify changes for Item2 here */
     }
     ${Item3} {
         /* Implement changes for Item3 here */
     }
}

In this instance, the @media rule is located outside of the styled-components block. Each styled component selector is included in the @media rule to dictate the modifications that should be implemented when the screen size is equal to or less than 768px.

This approach eliminates the need to repeat the media query for every styled component and allows you to define all alterations in one central location.

If you found this explanation helpful, please let me know!

Answer №2

Develop a master styled component that incorporates your media queries, then pass on the styling to other styled components through inheritance

Master media component:

    const MasterMediaComponent = styled.div`
        // Media Queries for all components
   `

Other components inheriting styling from the master media component:

    const MainContainer =  styled(MasterMediaComponent)`
        // Styling for main container component
`
const ListContainer =  styled(MasterMediaComponent)`
       // Styling for list container component
`

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

CSS - ensure that two elements with display: table-row stay stacked on top of one another

I came across this HTML structure .table { display: table; } .row { display: table-row; } .cell { display: table-cell; text-align: center; padding: 5px; border-right: 1px solid #ddd; border-bottom: 1px solid #ddd; } .sticky { positi ...

To install the React Native command line interface, use the following command:

Hello, I am encountering an issue while trying to install React Native. When running npm install -g react-native-cli, Command Prompt displays the following error: npm ERR! code EINVAL npm ERR! path C:\WINDOWS\system32\'C:\Users&bso ...

The import failed because the 'ImageList' is not accessible from the '@material-ui/core'

Hey there! I'm currently working on a React app and I am having some trouble importing ImageList from @material-ui. I tried using "import { ImageList } from '@material-ui/core'; but it's giving me an error during compilation. I hav ...

What steps should I take to ensure that the navbar is responsive and mobile-friendly?

After creating a navigation bar in an ejs file, I included it in all the files. The issue is that it looks fine on desktop view but does not respond well on mobile devices. There is some space left on the screen and it's not utilizing the entire width ...

Navigate back to the previous URL and remove any search parameters using React-router-dom V6

After navigating to a page with certain search parameters, I needed to go back to the previous URL and clear the search params. To achieve this, I utilized the useSearchParams function provided by react-router-dom v6. Within the useEffect hook, I implemen ...

Issue with React rendering numbers without displaying div

In my user interface, I am attempting to display each box with a 1-second delay (Box1 after 1 second, Box2 after another 1 second, and so on). https://i.sstatic.net/FdTkY.png However, instead of the desired result, I am seeing something different: https ...

What is the method for increasing the left margin of the back button on the default header in React Native?

My attempt to increase the space on the back button from the left side of the header in my React Native code has been unsuccessful. headerStyle: { paddingLeft: 60 } https://i.stack.imgur.com/0RFb0.png I also experimented with adding margin ...

Setting the maximum height for a div element

Struggling to understand how a div can occupy the entire height of a container. In this particular scenario, I am aiming for the "photo" div to take up the full height, with the yellow and green content appearing on the right side of the photo. Below is th ...

What is the process for having an object act as a child element?

Currently in the process of learning React/Next.js. A main layout that includes two components - footer and header, has been created. function MainLayout(children) { return( <div> <Header /> {children} ...

Personalize or delete the spacing within an ion row

Currently, I am delving into the world of Ionic app development. Although I have grasped the concept of the Grid layout, I find myself hitting a roadblock when it comes to adjusting or removing spaces between rows 2 and 3 in my app interface, as illustrate ...

Utilize React to display a Selected button within a whitespace

Currently, I am encountering an issue in React where I have a group of buttons at the bottom. Upon selecting a button, the corresponding text should display at the top within a specified whitespace. However, I am looking to have the whitespace already occu ...

Blurring and masking an image within a hollow circle shape

I'm currently working on developing a similar example using react-native-svg. The background image I am using is dynamic and needs a transparent circular mask. Additionally, I want to apply a blur effect to that specific section of the background ima ...

The dimensions of the box remain fixed and do not change when the screen is resized

Just starting out with HTML and CSS and trying to create a responsive website. Running into an issue where the black striped box on my page is not moving up when I resize the screen. It appears to be stuck in place, causing a gap between it and the slide s ...

Changes will not reflect until a re-deployment is done on Next.js 13 and Sanity

Hey there! Currently, I'm using Next.js version 13 with server components by utilizing the /app directory along with Sanity Studio. Here's a snippet of my code: const Page = async () => { const query = groq`*[_type == "university"] ...

This error occurs because the argument type 'AsyncThunkAction<any, void, {}>' cannot be assigned to a parameter of type 'AnyAction'

I encountered an error that I couldn't find a solution for on Stack Overflow The argument of type 'AsyncThunkAction<any, void, {}>' is not compatible with the parameter of type 'AnyAction'. <MenuItem onClick={() =&g ...

Insider's guide to showcasing code in vibrant colors using Python Django

Context: I am currently working on a Python Django web application and need to showcase code snippets in the browser with syntax highlighting. An example of the code snippet I want to display would be: if True: print("Hello World") I am look ...

Use CSS3 to hide the <li> elements initially and make them appear when the <li> is clicked on

Click here How can I hide the "subline" line from the list and make it visible when the user clicks on the "sub" line, pushing the other lines down? I'm hoping for a solution that doesn't involve using Js or JQuery. Thank you in advance! ...

Aligning a picture at the center of the screen with CSS - Various screen and image sizes

For my project, I need to design a web page with a single image perfectly centered both vertically and horizontally on the screen. Here are the specific requirements: The client's screen size is unknown (mobile) The image will be user-defined with u ...

Achieving the optimal camera position directly above a .glb model in react-three-fiber: A step-by-step guide

Hey there! I've got a codesandbox demo ready for you, where I'm trying to troubleshoot something. So, I created a basic 3D model in blender and exported it. My aim is to bring this model into my React app using react-three-fiber, and have the ca ...

Customize the focus and selected background color of Material UI Select component

I am trying to customize the background color of a Select component and its MenuItems. Specifically, I want to remove or override the default background color of the focused Select component and selected MenuItem. The current background color of the selec ...