Conditionally render list with Higher Order Component

流过昼夜 提交于 2020-05-19 04:49:54

问题


My app has a feature toggle functionality that tells my UI whether or not a piece of UI should be rendered. I would like to create a Higher Order Component to conditionally render these types of components. In one scenario, I'm trying to conditionally render a list, but I'm running into this error:

ConditionalRender(...): A valid React element (or null) must be returned. You may have returned undefined, an array or some other invalid object.

This makes sense since I just am trying to render the children of this component. Here's what I've got so far:

https://jsfiddle.net/fmpeyton/cykmyabL/

var settings = { showHello: true, showGoodbye: false};

function ConditionalRender (props) {
    var output = null;

  if(props.shouldRender) output = props.children;

  console.log(output);
  // return (<li>{output}</li>); // This works, but isn't desired html structure
  return ({output});
}

function App (props) {
    return (
    <ul>
        <ConditionalRender shouldRender={props.settings.showHello}>
        <li>Hello!</li>
      </ConditionalRender>
      <ConditionalRender shouldRender={props.settings.showGoodbye}>
          <li>Goodbye...</li>
        </ConditionalRender>
    </ul>
  );
}

ReactDOM.render(
  <App settings={settings} />,
  document.getElementById('container')
);

If I can help it, I would just like to render the children without any additional logic.This HOC would also handle more complex children down the line. Something like this:

<ConditionalRender shouldRender={props.settings.showHello}>
<div>
<p> blah blah blah</p>
<table>
<!-- ... -->
</table>
</div>
</ConditionalRender>

Any ideas?


回答1:


Try this:

function App(props) {
  return (
    <ul>        
      {props.settings.showHello && <li>Hello!</li>}
      {props.settings.showGoodbye && <li>Goodbye...</li>}
    </ul>
  );
}

P.S. Your code doesn't work because of this line:

return ({output});

Assuming you have es2015 support, it would be treated as object property shorthand. So it's the same as:

return {output: output};

which is not what React expects to get from the render method.

You could try this:

function ConditionalRender(props) {
  if (props.shouldRender) {
    // Make sure we have only a single child
    return React.Children.only(props.children);
  } else {
    return null;
  }
}

But this is not the simplest way. See more here.

P.P.S. Your ConditionalRender component is not what is called Higher-Order Component. According to the docs, HOC is a function that takes a component and returns a new component.



来源:https://stackoverflow.com/questions/42080459/conditionally-render-list-with-higher-order-component

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!