W
W
wonderingpeanut2022-04-16 09:41:21
css
wonderingpeanut, 2022-04-16 09:41:21

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>
  )
}

Question: which is better? Why is one better than the other and in what cases/indicators? Maybe go ahead and use BOTH conditional rendering and media queries??

I think it would be better to use different display values ​​through media queries, because it will be cheaper than conditionally rendering one element or the second.
OR NOT? In theory, the application does not change the screen width so often during use, and rendering one element is probably faster than rendering two elements

. In general, DISCASSS.

Answer the question

In order to leave comments, you need to log in

1 answer(s)
W
wonderingpeanut, 2022-04-16
@wonderingpeanut

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 question

Ask a Question

731 491 924 answers to any question