Search code examples
htmlreactjscomponentshideshow

React js how to show clicked div and delete previous div content


Hello i have a question if some one could help.

I created a react app with tree buttons when i click on every button the code shows and hide text.

But i wanted when i click for example on button 2 the text from button 1 and 3 to be hidden. And the same for every button if i click on button 3 the text from button 1 and 2 to be hidden also.


import React, { useState } from 'react';

export default class Tinfo extends React.Component{
    constructor(props){
       super(props);
       this.state = { show: new Array(3).fill(false) };
       this.baseState = this.state 
    }

    resetState = () => {
        this.setState(this.baseState)
      }

    toggleDiv = (index) => {
       var clone = Object.assign( {}, this.state.show );
       switch(clone[index]){
          case false:
          clone[index] = true
             break;
          case true:
             clone[index] = false
             break;
       }
       this.setState({ show: clone });
    }



    render(){
       return(
     <div>
          { this.state.show[0] && <div id="tinfo"> First Div </div>}
          { this.state.show[1] && <div id="tinfo"> Second Div </div>}
          { this.state.show[2] && <div id="tinfo"> Third Div </div> }
          <button onClick={() => this.toggleDiv(0)}>button 1</button> 
          <button onClick={() => this.toggleDiv(1)}>button 2</button>
          <button onClick={() => this.toggleDiv(2)}>button 3</button>
     </div>

       )
    }
 }



Solution

  • since only one can be shown, then just reset the state

    toggleDiv = index => {
      const show = new Array(3).fill(false);
      show[index] = true;
      this.setState({
        show
      });
    }
    

    although this should now be named showDiv as it sets the state and hides the rest, it's not a toggle.