0
votes

I want to hide the content or JSX of Parent component and show JSX of child component when some button is clicked.

There are two components ABC and XYZ.

Desired behavior: when button is clicked XYZ component should be rendered within the same div with className sidebar, but JSX of component ABC should be hidden now.

Currently, when I click button, XYZ renders while ABC is still there.

Any ideas, how can I achieve this?

class ABC extends React.Component {
  render() {
    <div className="sidebar">
     <h1>This is component ABC</h1>
    </div>
  }
}

class XYZ extends React.Component {
  render() {
    <div className="sidebar">
      <h1>Replaced by XYZ</h1>
    </div>
  }
}
1
use conditional rendering buttonClick === true ? XYZ : ABC - Dostonbek Oripjonov

1 Answers

2
votes

You can render <XYZ /> or <ABC /> depends on isClicked flag.

Below codes show how to render each child component in certain condition.

class Parent extends React.Component {
  state = { isClicked: false };
  render() {
    <div className="sidebar">
      { this.tate.isClicked ? <XYZ /> : <ABC /> }
    </div>
  }
}

Then you need to update isClicked flag in parent component.