Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

`display: none` vs conditional render in React

I'm having trouble deciding the difference between these two patterns of rendering in React. Hopefully someone can shed some light on this matter.

Pattern 1: React's Conditional Render

https://facebook.github.io/react/docs/conditional-rendering.html

class List extends React.Component {
  state = {
    menu: false,
  }
  handleMouseOver = () => {
    this.setState({
      menu: true
    });
  }
  handleMouseLeave = () => {
    this.setState({
      menu: false
    });
  }
  render() {
    const { menu } = this.state;

    return (
      <li
        onMouseOver={this.handleMouseOver}
        onMouseLeave={this.handleMouseLeave}
      >
        {menu && <Menu />}
      </li>
    );
  }
}

Pattern 2: display: none

.menu {
  display: none;
}

.li:hover .menu {
  display: block;
}
const List = () => (
  <li className="li"><Menu className="menu"/></li>
);

Question:

If I need to render 100 of these items in a single page, which pattern should I go for?

How can I determine which pattern is better?

Are there any performance benefit of using one over the other?

like image 791
cusX Avatar asked Mar 29 '17 12:03

cusX


People also ask

What is conditional rendering in React?

In React, you can create distinct components that encapsulate behavior you need. Then, you can render only some of them, depending on the state of your application. Conditional rendering in React works the same way conditions work in JavaScript.

What does ReactDOM render do?

The ReactDOM. render() function takes two arguments, HTML code and an HTML element. The purpose of the function is to display the specified HTML code inside the specified HTML element.

Which operator can be used to conditionally render a React component?

Logical && Operator Another way to conditionally render a React component is by using the && operator.


1 Answers

I tend to use display: none in situations where there's a simple condition to show something (e.g hover, etc). If it's a bit more complex (e.g. click a checkbox to hide an element) then I go with conditional rendering. The reason behind this is that I don't want to cause state changes and trigger an update for something as trivial as a hover state, and don't want to fiddle around with obscure css classes for things that will have to involve code anyway.

Again, this is my personal preference.

TL;DR: CSS if super simple (e.g. hover), conditional​ render if more logic involved

like image 95
Daniel Pedroso Avatar answered Sep 23 '22 09:09

Daniel Pedroso