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?
You dont need to create an extra function for it.
This will do the job:
class App extends Component {
render() {
return (
<div>
{this.props.shouldRenderCounter && <Counter />}
</div>
);
}
}
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.
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.