简体   繁体   中英

How can I remove a component using the children prop in React

I am trying to achieve this scenario:

  1. I have Foo component with bar prop

  2. If bar prop is true --> mount Bar component that is inside the Foo component

  3. if bar prop is false --> unmount Bar component
  4. I don't want Example component to be aware of this show/hide, I want only Foo to know when to show or hide it
  5. Bar is not necessary a direct child of Foo, it can also be nested deeper in the children of Foo
 const Example = () => { return ( <Foo bar={true/false}> <div>some div</div> <Bar></Bar> </Foo> ) }; class Foo extends React.Component { componentWillReceiveProps({bar}) { if (bar) { /* I want to show bar!! */ } else { /* I want to remove only bar!! */ /* maybe doing something like: this.props.children.searchForBar().removeNode() */ } } render () { return ( <div>{this.props.children}</div> ) } }; const Bar = () => 'I am some bar'; 

I've tried to manipulate this.props.children but React blocked me from modifying children myself.

Do I need maybe an outer service for communication between these 2 components ?

Should I use context maybe ?

Looking for an advice on how to approach this issue.

One of possible solutions is to use some kind of message bus or pubSub. In that kind of approach, Bar component would have to subscribe to the bus, and show/hide itself. Foo component would publish appriopriate messages in componentWillReceiveProps. More: here

One simple solution is to use Bar component inside of the Foo component and render that based on a ternary condition .

Also return a JSX element(Valid react element from Bar component) rather than a string.

 const Example = () => { return ( <Foo bar={true}> <div>some div</div> </Foo> ) }; class Foo extends React.Component { render () { return ( <div> <div>{this.props.children}</div> {this.props.bar? <Bar />: null} </div> ) } }; const Bar = () => <div>I am some bar</div>; ReactDOM.render(<Example/>, document.getElementById('app')); 
 <script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react.js"></script> <script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react-dom.js"></script> <div id="app"></div> 

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM