I want to conditional render component on button click, I wrote the following code but it\'s not working, when I click on comic, the comic component should be loaded, and wh
Your .render
must return the components that you want to show.
So the code should look something like --
let component = this.state.buttonId === 2 ? <Contest/> : <Comic/>
return(
<>
{component}
<div>
{/* your button here */}
</div>
</>
);
You are not returning your components, try the following:
class Head extends Component{
constructor(){
super();
this.state = {
buttonId: null
}
this.setButton = this.setButton.bind(this);
}
setButton(id){
this.setState({buttonId: id});
}
render(){
return(
<div>
{this.state.buttonId === 1 && <Comic/>}
{this.state.buttonId === 2 && <Contest/>}
{this.state.buttonId !== 1 && this.state.buttonId !== 2 && <Comic/>}
<input className={this.state.buttonId === 1? "button1 orange" :
"button1"} onClick={() => this.setButton(1)} value="Comic"
type="button" ref="button" />
<input className={this.state.buttonId === 2? "button2 orange" :
"button2"} onClick={() => this.setButton(2)} value="Contest"
ref="button1" type="button" />
</div>
);
}
}
export default Head;