Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Early returns in React sub render function: return null, [], or React.Fragment?

Let's say I have a simple component that may or may not render a Counter.

What's the best practice in React to express a blocked code path? Should it return null, [], or a Fragment?

class App extends Component {
  renderCounter() {
    if (!this.props.shouldRenderCounter) {
      // // which should I return?
      // return; 
      // return null; 
      // return []; 
      // return <React.Fragment />; 
    }
    return <Counter />;
  }

  render() {
    return (
      <div>
        {this.renderCounter()}
      </div>
    );
  }
}

I think null is the clearest, but I can imagine it causing problems if the context around the return function expects a component. [] and Fragment both seem like fine options to me, except Fragment is a little easier to read. What's the difference?

like image 746
Tai Avatar asked Nov 28 '18 17:11

Tai


1 Answers

Returning null is recommended by the React team:

In rare cases you might want a component to hide itself even though it was rendered by another component. To do this return null instead of its render output.

like image 126
Owen Pearson Avatar answered Sep 24 '22 13:09

Owen Pearson