Is there a way to find out if ReactElement displays "null"?

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

A sample code (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 there any way to check elemA.isNull() ?

+8
javascript reactjs react-jsx
source share
3 answers

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

Something like:

 if (AUtils.isStoryValid(story)) { return <A story={story} />; } else { return <B story={story} />; } 
+3
source share

You can use the following higher order component (HOC) to intercept the ElementA rendering method and accomplish what you want:

 function withNullCheck(WrappedComponent) { return class NullChecker extends WrappedComponent { render() { const result = super.render(); return( <div> { this.props.alwaysPrefix } { result && this.props.ifNotNullPrefix } { result ? result : this.props.ifNull } { result && this.props.ifNotNullAppend } { this.props.alwaysAppend } </div> ); } } } 

You would use it as follows:

 const NullCheckedElementA = withNullCheck(ElementA); ... function render() { return ( <NullCheckedElementA alwaysPrefix={someElements} ifNotNullPrefix={elemB} someProp={this.someVar} /> ); } 
+1
source share

So, I came across a situation where I was stuck to do this, here is a way that works (although hacking can make you cry).

It should be used only as a last resort, because it is really a complete hack, and you will achieve success in 0-20 ms depending on the complexity of the component. (The vendor assumes that you are using reduction, and your component depends on your reduction state):

 import { renderToStaticMarkup } from 'react-dom/server'; import { Provider } from 'react-redux'; import store from 'pathToYourReduxStoreInstance'; export default function isRenderingNull(componentInstance) { return !renderToStaticMarkup( <Provider store={store}> {componentInstance} </Provider> ) } 
0
source share

All Articles