Sometimes, we want to render a new React component on click in our React app.
In this article, we’ll look at how to render a new React component on click in our React app.
Render New React Component on Click
We can render a new React component on click if we set a state so that the component can be rendered.
For example, we can write:
class App extends React.Component {
constructor(props) {
super(props);
this.state = {
showComponent: false,
};
this.onClick= this.onClick.bind(this);
}
onClick() {
this.setState({
showComponent: true,
});
}
render() {
return (
<div>
<button onClick={this.onClick}>click me</button>
{this.state.showComponent ?
<Foo /> :
null
}
</div>
);
}
}
We have a button that runs the this.onClick method on click.
It changes the showComponent state to true .
Then we can make the Foo component show when this.state.showComponent is true .
Conclusion
We can render a new React component on click if we set a state so that the component can be rendered.