Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is there a way to tell if ReactElement renders "null"?

In my JSX, I have a case of a conditional rendering logic - when element A renders something (it's render() function returns something other than null), then also render element B, just above the element A.

Code example (simplified) would look like this:

function render() {     let elemA = (<ElementA someProp={this.someVar} />);      if (elemA.isNull()) {         return (             <div>                 { ...someElements }             </div>         );     }      return (         <div>             { ...someElements }             <ElementB />             { elemA }         </div>     ); } 

So my question is - Is there any way to have the elemA.isNull() check?

like image 642
mdziekon Avatar asked Oct 14 '15 22:10

mdziekon


People also ask

How do you know if a component is returning null?

If its prop isTrue is false-y, then the component returns null , and React doesn't render anything. I need to test it as a component, mount it, pass the prop, and test if it's children is getting rendered when the prop isTrue is truth-y, or we are getting null if isTrue is false-y.

How do you check if element is rendered React?

There's a checkbox well hidden in the React DevTools settings that allows you to visually highlight the components that rerendered. To enable it, go to "Profiler" >> click the "Cog wheel" on the right side of the top bar >> "General" tab >> Check the "Highlight updates when components render." checkbox.

What happens if your return NULL instead of the JSX?

The condition in the example checks for the value of the count state variable and if it's greater than 3 , it returns null . If you return null from a component, nothing is rendered. You can also return null to render nothing from a JSX expression.

How do I know if my React element has children?

you can check if the component has children by reading the children prop, along with the React. Children. count the code would be: function ContextMenuItems({ children }): JSX.


1 Answers

No, there's no way to determine what a child will render using React. The standard way to do this is to expose some utility function that says whether A will render.

Something like:

if (AUtils.isStoryValid(story)) {   return <A story={story} />; } else {   return <B story={story} />; } 
like image 88
Sophie Alpert Avatar answered Sep 18 '22 17:09

Sophie Alpert