What is the best way to modify React state?

Can someone help me troubleshoot an issue with toggling React state after a button click? I want to be able to change "Work From Office" to "Work From Home" and vice versa, but it's only working once. Is there a way to achieve this using an if statement or is there a simpler solution?

 ** 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 class="schedule change">
                        <h3>Emplyoee Name: </h3>
                        <p>Today Pooja is work {this.state.work}</p>
                        {/* <button class="chageScheduleBtn " onClick = {()=> this.changeMyWorkPlace()}> Change My Schedule </button> */}
                        <button class="chageScheduleBtn " onClick = {()=> this.workFromOffice() ?'Home': 'Office'}> Change My Schedule </button>
                    </div>
                </div>
            )
        }
    }
    
    export default ChangeSchedule;

Answer №1

To manage different states, consider using a ternary expression to show specific content.

Here is an example:

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

Your button should now function as intended:

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

For a complete working demonstration, check out this codesandbox example.

Answer №2

To achieve this functionality, you can modify the code as shown below. Simply update the status on click events and utilize a ternary expression within the button:

import { Component } from "react";
import "./ChangeSchedule.css";

class ChangeSchedule extends Component {
  constructor() {
    super();
    this.state = {
      workFromOffice: true,
    };
  }

  changeMyWorkPlace() {
    this.setState({
      workFromOffice: !this.state.workFromOffice,
    });
  }

  render() {
    return (
      <div>
        <div class="schedule change">
          <h3>Employee Name: </h3>
          <p>Today Pooja is working {this.state.work}</p>
          <button class="chageScheduleBtn " onClick={() => this.changeMyWorkPlace()}>
            {this.state.workFromOffice ? "Work From Home" : "Work From Office"}
          </button>
        </div>
      </div>
    );
  }
}

export default ChangeSchedule;

Answer №3

To simplify your state management, consider focusing on a single entry such as workFromOffice. Your click handler can then easily toggle the value of this entry. Here's an example:

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

Answer №4

Each time you run the changeMyWorkPlace function, it captures your initial state and uses it. This means it only works once unless you instruct React to use the most up-to-date state. Try this approach:

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

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

React: Issue accessing URL parameters using useParams() within a nested component

In my demo application, there are two components - QuoteDetail and Comments. Both require URL parameters, but I am only able to access them in the parent component. App.tsx: <Switch> // ... <Route path="/quotes" exact> <Al ...

How to show a tooltip inline by utilizing CSS styling

Working on a sticky side bar menu with a tooltip feature. While it appears correctly in Chrome and Safari, the tooltip is off-center in IE. This snippet seems to be causing the issue: /* Vertically center tooltip content for left/right tooltips */ .tool ...

If the user is not currently logged in, refrain from attempting to elicit a reaction from them

Well, this question may appear to be quite straightforward. I did some research on Stack Overflow to find if someone else had a similar question, but it turned out that there weren't any. My tech stack involves React for the front end and a NodeJS ba ...

The issue with 'DemoCtrl' defined in Angular JS is that it does not correspond to a valid argument

signup.html <div ng-controller="UniqueCtrl" layout="column" ng-cloak="" class="md-inline-form inputdemoBasicUsage" ng-app="inputBasicDemo"> <md-content md-theme="docs-dark" layout-gt-sm="row" layout-padding=""> <div> <md- ...

Tips for leveraging Backbone.js for creating dynamic single page websites

I am eager to create my own personal website with a unique functionality similar to this example: The idea is to have the entire website contained within a single HTML page, where clicking on a navigation item will dynamically load only the necessary info ...

The overlay only covers a portion of the page

I'm currently working on a new webpage and have found the perfect background image. However, I would like to add an overlay to darken the image. Unfortunately, the overlay doesn't cover the entire page! Despite my attempts, I haven't been s ...

Is the background image unable to fill up the entire screen?

I'm currently facing an issue with my webpage's background not covering the entire vertical space. Despite trying different solutions and referring to previous posts, I haven't been able to resolve it yet. Here is the relevant code: <div ...

Float over Material UI Icon and Text

Currently, I am tackling a React JS Project. My task involves creating a breadcrumb that contains both text and an icon. To accomplish this, I have incorporated a material UI icon. import UpdateIcon from "@material-ui/icons/Update"; ...

Dealing with empty parameters in NextJs and dynamic routes: What's the best approach?

Is there a way to retrieve the URL parameter without using query strings? For example, in the URL http://localhost:3000/test/1, how can we extract the parameter without facing a 404 page when it's omitted? Directory Structure test - [pageNumber].js ...

Using React and TypeScript to enable file uploads

Seeking assistance in creating a basic single select upload component. When I click a button that contains a hidden input field, the file dialog opens and allows me to choose a file. The placeholder then changes to display the selected file name along with ...

Break apart PDFs into individual images or convert to HTML

I'm currently working on a project that requires the development of a unique webtool. The purpose of this tool is to allow users to effortlessly upload their PDF documents, which will then be displayed in a browser with an engaging page flip effect ut ...

Top tips for seamless image transitions

Currently working on a slideshow project and aiming to incorporate smooth subpixel image transitions that involve sliding and resizing, similar to the Ken Burns effect. After researching various techniques used by others, I am curious to learn which ones ...

A common occurrence is for jQuery/Javascript Ajax POST to generate 6 identical posts when used within a .each loop, happening approximately 20

Context: Building a jQuery mobile phonegap application with multipage-ajaxload and sisyphus enabled form that utilizes an AJAX POST loop to interact with a GUI database. The process involves posting 171 section entries, along with one summary entry to a se ...

Element in list displaying a distinct alignment from the rest

I currently have a navigation bar based on a list, which looks something like this: https://i.stack.imgur.com/e1Dmb.png My concern is how to position the "Logout" item on the right side of the screen. I've tried adding clear list items but that seem ...

Chosen option from the Bootstrap drop-down menu

Struggling with two problematic input fields on my Bootstrap website... The first is a Bootstrap Typeahead input field: <input type="text" id="typeahead" name='name' placeholder='The name' class="form-control" data-provide="typeahe ...

Guide on integrating right-click functionality for a list item in Material UI using ReactJS

I'm currently working on a React.js application with Material UI. I have successfully added onClick functionality to my List and List Item components. enter image description here Now, I am looking to implement an onRightClick event as well. Can someo ...

Is there a way to verify an email address and transfer form data to a different HTML page for printing?

How do I troubleshoot email validity checking issues in my form? It works fine when no characters are entered, but fails when characters are inputted. What could be causing this problem? Additionally, I want to open a new HTML sub-file after form submissi ...

Setting the height of a Bootstrap radio button

My Bootstrap radio buttons are set to a width of 200px. However, when the text inside the button exceeds this width, it wraps onto two lines leading to changes in button height. How can I ensure that all other buttons displayed scale to the same height? h ...

Preventing specific time intervals from being selected in the MUI time picker component of a ReactJS application

Can MUI time picker disable specific minutes within certain hours? For instance, I'd like to prevent the selection of minute 30 in hour 5 only. Users should not be able to choose the time 5:30, but they should still have the option to select the 30th ...

I am experiencing an issue where my JavaScript code does not redirect users to the next page even

I'm experiencing an issue with this code where it opens another webpage while leaving the login screen active. I've tried multiple ways to redirect it, such as window.location.href and window.location.replace, but nothing seems to be working. Ide ...