Is there a way to tell if ReactElement renders “null”?

ぐ巨炮叔叔 提交于 2019-12-05 00:31:27

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} />;
}

You can use the following higher order component (HOC) to intercept the render method of ElementA 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 like this:

const NullCheckedElementA = withNullCheck(ElementA);

...

function render() {

    return ( 
      <NullCheckedElementA 
         alwaysPrefix={someElements} 
         ifNotNullPrefix={elemB} 
         someProp={this.someVar} 
      />
    );

}

So I ran into a situation where I was stuck having to do this, here is a way that works (though the hackiness might make you cry).

Should only be used as a last resort because it really is a total hack and you'll take a ~0-20ms performance hit depending on component complexity. (Provider is there assuming you're using redux and your component depends on your redux 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>
  )
}
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!