1

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
            }
The Walrus
  • 1,148
  • 6
  • 28
  • 46

1 Answers1

9

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>
    )
}
Narasimha Reddy - Geeker
  • 3,510
  • 2
  • 18
  • 23
  • sorry one thing, if im passing stuff into a component like so: `
    ` how can i fix that? it says players is undefined and that is because players is relying on state (but i have just put all the above inside state?)
    – The Walrus Sep 26 '17 at 11:34
  • dont worry, fixed. moved it out of state – The Walrus Sep 26 '17 at 11:37