CustardBun
CustardBun

Reputation: 3857

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?

Upvotes: 22

Views: 26124

Answers (1)

klugjo
klugjo

Reputation: 20885

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

Upvotes: 26

Related Questions