Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Best practice for an "empty" component - null? empty div? (A valid React element (or null) must be returned)

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?

like image 496
CustardBun Avatar asked Nov 09 '17 01:11

CustardBun


People also ask

How do you return an empty component React?

To return nothing from a React component, simply return null . When null is returned from a React component, nothing gets rendered.

Can React components return undefined?

In React 18 (currently in alpha), components may render undefined , and React will render nothing to the DOM instead of throwing an error.

What happens when a component returns NULL from its render method?

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.

What is empty <> In React?

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.


1 Answers

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

like image 90
klugjo Avatar answered Sep 28 '22 00:09

klugjo