简体   繁体   中英

Is it better practice to conditionally render in React or conditionally add a class to hide elements

As far as my React experience has taken me so far, I have two methods of hiding some rendered HTML from a React components output/render based on props/state:

  • surround the HTML/JSX in question with some conditional logic, or
  • add a class to that element conditionally and let CSS control the display/visibility

I wonder which is best practice? I have a hunch that there may be some performance gain by using the CSS method as the browser doesn't need to manipulate the DOM as heavily. Alternatively, it's sometimes nice to have an element completely removed from the DOM.

Any insights?

I asked a similar question here and received a reply from Sophie Alpert, one of the members of React core team.

Basically in most cases it's better not to render the HTML at all if it should stay that way throughout the lifetime of that page. If frequent toggling is desired, then use CSS to show/hide the element.

From performance perspective: react intelligently minimizes DOM re-renders, including special treatment if you change a list of items (eg <li> items) in the DOM. And react is really fast. Haven't tested, but I would think any difference in performance would be minimal.

If the component in question is pure HTML, then I generally apply the following rule of thumb between the 2 ways of hiding elements:

  • for components which are part of UI that can be opened and closed multiple times by user (eg dropdown-menu, tooltips, popovers etc): use CSS hiding/ displaying, possibly with conditionally adding class in react.
  • for components rendered and hidden only once (eg delete an item from a list, close a one-time modal popup etc): use conditional rendering.

NB: For components that hold more than just HTML, eg components containing input fields or buttons, or for react components, it is better to let react remove them from the DOM. To let react also nicely clean up possible event listeners etc etc.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM