Skip to content
Advertisement

React How to change view after click on button

I wouldlike to change my view when I click on one Button :

render(){
        return(
          <div className="button-toolbar">
            <button className="button">Button 1</button>
            <button className="button">Button 2</button>
            <button className="button">Button 3</button>
            
            <View1></View1> 
            <View2></View2> 
            <View3></View3> 
          </div>
        )

For example when I click on the button 1, only View1 is active. If I click on Button 2 ==> View 2 If I click on Button 3 ==> View 3

PS : View1, View2 and View3 are component file (.jsx)

Advertisement

Answer

There are multiple ways to do this. You can set flags around the views. For example

render(){
        return(
          <div className="button-toolbar">
            <button className="button" onClick={() => setState({view: 1})}>Button 1</button>
            <button className="button" onClick={() => setState({view: 2})}>Button 2</button>
            <button className="button">Button 3</button>
            
            {this.state.view === 1 ? <View1></View1> : ''}
            {this.state.view === 2 ? <View2></View2> : ''}
            <View3></View3> 
          </div>
        )
Advertisement