How to remove / disable nested react components

I would like to disable one react component that belongs to the parent component containing three components. The parent component has this render function:

render: function () {
  return (
    <div className={classes}>
      <Navbar ref="navbar"/>
      <Home ref="home"/>
      <Footer ref="footer"/>
    </div>
),

handleNavbarClick: function () {
  // remove Home
}

      

if the user then clicks on the link in the navbar and I want to unmount the Home component, how do I do that? it seems like my only option is to do something like this (taken from react.js: component removal ), but that looks pretty crude:

render: function () {
  var home = this.state.remove_home ? null : <Home ref="home />
  return (
    <div className={classes}>
      <Navbar ref="navbar"/>
      {home}
      <Footer ref="footer"/>
    </div>
),

handleNavbarClick: function () {
  this.setState({remove_home: true});
}

      

Is this the appropriate way to respond?

+3


source to share


2 answers


Yes, your proposed solution

render: function () {
  var home = this.state.remove_home ? null : <Home ref="home" />
  return (
    <div className={classes}>
      <Navbar ref="navbar"/>
      {home}
      <Footer ref="footer"/>
    </div>
),

handleNavbarClick: function () {
  this.setState({remove_home: true});
}

      

is a more or less "correct" way to handle this with React. Remember, the goal render

is to describe how your component should look at any given point. When acquiring the DOM and performing manual operations, or doing other important work such as "removing" an element, you almost always have to do it wrong.

If you're worried about the syntax, you might consider inserting or extracting logic:

render: function () {
  return (
    <div className={classes}>
      <Navbar ref="navbar"/>
      {this.state.remove_home ? null : <Home ref="home" />}
      <Footer ref="footer"/>
    </div>
),

      



or

render: function () {
  return (
    <div className={classes}>
      <Navbar ref="navbar"/>
      {!this.state.remove_home && <Home ref="home" />}
      <Footer ref="footer"/>
    </div>
),

      

or

render: function () {
  return (
    <div className={classes}>
      <Navbar ref="navbar"/>
      {this.renderHome()}
      <Footer ref="footer"/>
    </div>
),

renderHome: function() {
  if (!this.state.remove_home) {
    <Home ref="home" />
  }
}

      

+4


source


try it



handleNavBarClick: function(){
    React.findDOMNode(this.refs.home).style.display = 'none';
}

      

0


source







All Articles