The Walrus The Walrus - 21 days ago 10
React JSX Question

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 null)

This is easy with 2 components. I just have a toggle function like so:

toggle() {
this.setState(prevState => ({
showTable: !prevState.showTable
}));
}


I have tried to adapt this for now where I have this:

showComponent(component) {
this.setState(prevState => ({
[component]: !prevState.component
}));
}


This currently shows the component when i click the corresponding button. However, it wont hide the component once the same button is clicked again.

I have all my buttons calling this method like so:

<button onClick={() => this.showComponent('AddPlayer')}>Add</button>
<button onClick={() => this.showComponent('ShowPlayers')}>Players</button>
<button onClick={() => this.showComponent()}>Table</button>
<button onClick={() => this.showComponent()}>Matches</button>


any ideas?

EDIT:

{this.state.AddPlayer ?
<div className="add-container">
<AddPlayer />
</div>
:
null
}
{this.state.ShowPlayers ?
<div className="players-container">
<Players />
</div>
:
null
}

Answer Source

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>
    )
}