Search code examples
reactjsreact-state-management

Changed State based on the key


I want to changed boolean state based on the value is passed

class Home extends Component {
  constructor(props) {
    super(props);
    this.state = {
      formElement: {
        home: true,
        booth: false,
        summary: false
      },
    };
  }

  buttonClickHandler(event, nextView) {  //nextView == summary
    // nextView == summary then summary would be true and booth would be flase and home would flase too
  }
}

Here based on nextView all state value should be reserved.

Thanks in advance..!!

Solution

  • considering you are receiving nextView as home/booth/summary and based on this you want to set corresponding key i.e. formElement[nextView] = true and for other keys i.e. formElement[!nextView] = false.

    You can try following:

    buttonClickHandler (event, nextView) {  
      const { formElement } = this.state;
      Object.keys(formElement).forEach(key => {
         this.setState({
           formElement: {
             ...formElement,
             [key]: key === nextView  // here will check if the current key matches nextView
           }
         });
      });
    }
    

    By the way I feel you might use simpler state variable, if possible. like

    this.state = {
          formElement: 'home'
    };
    

    then

     buttonClickHandler (event, nextView) {  
          this.setState({
            formElement: nextView
          });
       }
    

    It is just a thought for https://en.wikipedia.org/wiki/KISS_principle.