should i use media queries for responsive design with react?

Viewed 1061

I want to make a responsive website using react, should i use media queries for change layout and set display to 'none' for some components in mobile ( like regular html and css ), or do that in-react and don't render that component rather than don't display it using css ?

for example, for a menu, if user clicked on the menu button, change display property of menu from 'none' to 'block'

<ul id="menu">
    <li>one</li>
    <li>one</li>
</ul>

toggle the 'open' in the classList of the DOM Node

and in the css

.menu li {
    display: none;
}

.menu.open li {
    display: block;
}

or like this, use state and if user clicked on the menu button, change the state and make react to render the menu

[open,setOpen] = useState(false);

open?<Menu />:'';

which one is a better approach ? which one is recommended

and one more question, using 'refs' for accessing the DOM nodes in react is better than use traditional document.getElementById() ?

2 Answers

My initial reaction is that you probably aren't building anything that absolutely requires the most performant solution, so hiding an element via CSS versus eliminating it from the DOM via React is not going to matter much in the long run. My recommendation is do whatever you can to get your project complete and then worry about performance if your use-case warrants it.

With regards to your specific example, it is probably better to just toggle the element's existence with React versus applying a class to toggle the display property. My reasoning for that is because both operations will require a DOM manipulation (React would have to either add the list element or it would have to update the className value). Using a CSS class to toggle the display will also have a secondary task of applying the new display value which causes another reflow of the content.

React solution: Update DOM to insert new node.
CSS solution: Update DOM to add className. Reflow content based on new display property.

Regarding your second question about $refs...

Using $refs will be better than document.getElementById. The $refs object maintains an in-memory reference to HTML nodes that need to be manipulated. document.getElementById will require traversing the DOM tree to find the element, where as using $refs simply looks up the node via a named property.

If it's possible to do in CSS, always use CSS. JS is expensive than CSS in terms of loading and rendering. For your requirement, you need layout change depending on the device it's loaded. So use media queries and CSS Grids to do that without using JS. Refs is the react way to get DOM element. So please use that instead of using methods like document.getElementById().

Related