Toggle Component In React On Button Click
I have 4 components. I only want to render one at a time. I have buttons in my nav, when i click one it should render that component and then hide the other 3 (i.e. set them to nul
Solution 1:
You can do this in multiple ways,
One way is, create a const with all state values and components like
const components = {
"AddPlayer": <AddPlayer />,
"ShowPlayers": <Players />,
"Something1": <Something1 />,
"Something2": <Something2 />
}
set value to state like
showComponent(componentName) {
this.setState({displayedTable: componentName});
}
and inside render simply
render(){
return(
<div>
{components[this.state.displayedTable]}
</div>
)
}
Using Switch case
renderComponent(){
switch(this.state.displayedTable) {
case "AddPlayer":
return <AddPlayer />
case "ShowPlayers":
return <Players />
}
}
render () {
return (
<div>
{ this.renderComponent() }
</div>
)
}
Post a Comment for "Toggle Component In React On Button Click"