Home > other >  How to change / toggle React state?
How to change / toggle React state?

Time:06-26

I am trying to toggle react state after the button click. After clicking button Work From Office should change to work From Home and vice versa. But it is not working. What am I dong wrong? I am able to change only once. Can we do with if statement? What is simple way?

 ** React **
    import React, { Component } from 'react';
    import './ChangeSchedule.css';
    class ChangeSchedule extends Component {
    
    constructor(){
        super()
        this.state = {
        //    work:'from office'
        workFromOffice:true
          
        }
    }
    changeMyWorkPlace(){
 
        this.setState({ 
        //    work:'from Home'
        workFromOffice:!this.state.workFromOffice
        })
       }

        render(){
            return(
                <div>
                    <div >
                        <h3>Emplyoee Name: </h3>
                        <p>Today Pooja is work {this.state.work}</p>
                        {/* <button  onClick = {()=> this.changeMyWorkPlace()}> Change My Schedule </button> */}
                        <button  onClick = {()=> this.workFromOffice() ?'Home': 'Office'}> Change My Schedule </button>
                    </div>
                </div>
            )
        }
    }
    
    export default ChangeSchedule;

CodePudding user response:

You can use a ternary expression to display content for each state.

For example:

{this.state.workFromOffice ? " from Office" : " from Home"}

Now this button should work as you expect:

<button  onClick={()=> this.changeMyWorkPlace()}>
  Change My Schedule
</button>

See codesandbox for fully working example

CodePudding user response:

The answer is in the way you're structuring your state. You can make it really simple by just using one entry of the state - workFromOffice. Then, your click handler should care only about changing that state value to the opposite of what was set before. Example:

onClick={() => this.setState({ workFromOffice: !this.state.workFromOffice })}

CodePudding user response:

When the changeMyWorkPlace function created, it captures your initial state and uses it everytime you run the function so only works once. You should instruct react to use up to date state. try this way.

   changeMyWorkPlace(){
 
        this.setState((previousState) => ({ 
        //    work:'from Home'
        workFromOffice:!previousState.workFromOffice
        }))
       }
  • Related