Answer the question
In order to leave comments, you need to log in
Which is better and why: display property dependent on media query or conditional rendering dependent on screen width?
Greetings.
There is one section in the NEXT.JS application: on mobile it should be a carousel, and on desktop it should be a grid.
I’m sitting thinking about how best to do it: for both elements, set the display property, which for the carousel (max-width: 600px) will be block, for the carousel (min-width: 600px) it will be none, for the grid, respectively (max-width: 600) none, (min-width:600) flex
Or get the screen width via js (for example, through the same media query or innerWidth) and render either one element or another depending on the screen width.
In the application I use css-in-js solution (mui). The component looks something like this:
export const Section = () => {
// showCarousel будет true при ширине меньше 600px, false в противном случае
const showCarousel = useMediaQuery("(max-width: 600px)");
// Media-Query решение
return (
<Box>
{/* sx это media query для max-width: 600px, sm - для min-width: 600px */}
<Carousel sx={{ display: { sx: 'block', sm: 'none' } }} />
<Grid sx={{ display: { sx: 'none', sm: 'flex' } }} />
</Box>
)
// или так conditional rendering
return (
<Box>
{showCarousel ? (<Carousel />) : (<Grid />)}
</Box>
)
}
Answer the question
In order to leave comments, you need to log in
Thank you all for your active participation in this issue!
After rephrasing the question a bit, found the answer on stackoverflow
OUTPUT: conditional rendering > toggling JSX element properties
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question