I'm using typescript and react for a project and I have a case of nested components where I only want the inner component to result in content if some condition is true.
For example:
export const SomeOverview = (info) => {
... // some data manipulation
return (
<div>
<div><.... a bunch of stuff</div>
<SomeDetail data={data}/>
</div>
)
}
export const SomeDetail = (info) => {
...
if (<some condition using info) {
return (
<div>
<some content using info>
</div>
)
}
return null or <div/> ?
}
I can't just not return anything if I don't go into the if statement or else I get the react element error.
So for now I had tried putting in an empty div but it seems kind of like a hack. Is there a "better" way of accomplishing?
To return nothing from a React component, simply return null . When null is returned from a React component, nothing gets rendered.
In React 18 (currently in alpha), components may render undefined , and React will render nothing to the DOM instead of throwing an error.
As I understand it correctly: component returns null , so that there's nothing to mount in the DOM tree and componentDidMount should not be fired. Its not just about rendering, there are instances where you can use the React component lifecycle methods to take other action.
The React framework offers a shorthand syntax for fragment components that appears as an empty tag: <></> . While it is supported in JSX syntax, it is not part of the HTML standard and thus is not supported natively by browsers.
Returning null
is the way to go.
From the official documentation:
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.
https://reactjs.org/docs/conditional-rendering.html#preventing-component-from-rendering
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With