Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Determine if react component is null

I have a component that renders if some conditions are met, otherwise it returns null.

I'd like to know how to determine if the component is returning null from its parent.

I have tried logging the component to see what properties are changing when it is rendered or when returning null but can not detect any difference.

Any suggestions?

like image 930
oldo.nicho Avatar asked Jan 29 '17 15:01

oldo.nicho


People also ask

How do you check if something is null in React?

To check for null in React, use a comparison to check if the value is equal or is not equal to null , e.g. if (myValue === null) {} or if (myValue !== null) {} . If the condition is met, the if block will run. Copied!

Is null or empty in React?

To check if a variable is null or undefined in React, use the || (or) operator to check if either of the two conditions is met. When used with two boolean values the || operator returns true if either of the conditions evaluate to true . Copied!

How do you know if props are undefined?

If you need to check if a prop was passed to a component outside of its JSX code, compare the prop to undefined . Copied! const Button = ({withIcon}) => { if (withIcon !== undefined) { console.

What is null in React?

When you say null means you are not passing any props to that component. ~~ type in React. createElement can be a string like h1 , div etc or a React-Component.


Video Answer


1 Answers

You can just use a fallback prop.

Instead of:

function Child(){
 if(something) return null

 return <div>content</div>
}

function Parent(){
 // try to find out if child is null
 return <Child />
}

Just do:

function Child({ fallback = null }){
 if(something) return fallback

 return <div>content</div>
}

function Fallback() {
 return 'some fallback'
}

function Parent(){
 return <Child fallback={<Fallback />} />
}
like image 101
Aral Roca Avatar answered Sep 23 '22 17:09

Aral Roca