Returning An Empty React Component
React
27/03/2023
If you wish to return an empty React component, return either true
, false
, null
, or undefined
. These are all valid React nodes and are ignored when rendering the DOM.
JSX
<div>{true}</div>// Is the same thing as:<div></div>
A caveat to take note of is that certain "falsy" values are still rendered by React, such as the number 0
or an empty string ""
. Therefore, if you do conditional rendering with the &&
operator, you may run into some surprises.
JSX
<div>{props.messages.length && <MessageList messages={props.messages} />}</div>// When `props.messages.length` is `0`, the number `0` is rendered instead of nothing.
To avoid these surprises, Kent C. Dodds recommends using ternaries rather than &&
in JSX.
JSX
<div> {props.messages.length ? <MessageList messages={props.messages} /> : null}</div>// Will render `MessageList` only if `props.messages.length` is not 0.
- React Element vs JSX Element vs React Node vs React Component
- How To Properly Add Google Analytics in NextJS