9

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?

7
  • curious as to why you want to determine null from a parent? Commented Jan 29, 2017 at 15:26
  • In my app I have <Navbar /><Settings /><Content /> I want to determine whether the settings bar renders. If it returns null then I need to add padding to the content component so that the navbar doesn't overlap the content. If the settings bar does render then the padding is not required. I've solved the problem for now by returning a spacer the height of the navbar from the settings component instead of null, but have decided to leave this question up given that it could be handy to know how to do what I was enquiring about. Commented Jan 29, 2017 at 15:47
  • u can do one thing assign some id or className to setting component, then by using getElementById or class u can check how many children it has, in case of null it will have nothing i guess, i think it should work. Commented Jan 29, 2017 at 15:50
  • 1
    yes, you should be able to accomplish this with css alone. since components are modular, only they know whether they return null. That is an important boundary in the abstraction. You probably could extract a rendering function and then check the result, but this isn't a good pattern in general. Commented Jan 29, 2017 at 15:53
  • 1
    Possible duplicate of Is there a way to tell if ReactElement renders "null"? Commented Mar 7, 2017 at 13:54

1 Answer 1

1

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 />} />
}
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.