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.