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

How to send parameters to Bootstrap modal using a hyperlink

I need help confirming the deletion of a datatable row using a Bootstrap modal dialog. When a user clicks on the delete link, I want a modal to appear asking for confirmation. Here is my code: <c:forEach items="${equipes}" var="equ"> ...

Insert item at the end of the box and move all elements upwards

Hello! I'm experimenting with creating something using javascript's createElement method. My goal is to achieve an effect similar to this image: https://i.stack.imgur.com/itKUK.gif Currently, my code is functional, but the animation goes from to ...

Is there a way to rearrange html elements using media queries?

Here is a snippet of code showcasing how my website is structured for both desktop and mobile views. Display on Desktop <body> <div> <header> <div>example</div> <a><img src"my logo is here"/& ...

Whenever I adjust the layout of the navigation bar, the edges end up getting clipped

I'm having trouble with the border shape of my navbar. When I try to make it a rounded pill shape, the edges get cut off instead of being properly displayed. https://i.stack.imgur.com/sUN2Y.png Below is the HTML template: <template> <div cl ...

Creating a Reactjs application for an image slider that utilizes two child components

Currently, I am facing an issue with the display of selected images in my two child components that are being called from App.js. The problem lies in setting the currentIndex value properly within the child components. My main requirement is to have the im ...

The session name has not been properly defined

Sorry for any errors in translation. I'm facing an issue where the session name I insert is coming up as undefined. However, when I manually enter the username, everything works fine. View Image <? php session_start (); echo var_dump ($ _SESSION ...

"Implementing a onClick method to render a component in React with passed props – a complete

Is there a way to properly update the LatestTweetsComponent with data fetched in handleRequest? The `tweets` are correctly updating onClick, but the LatestTweetsComponent is not rendering or updating as expected. It seems like my current approach might b ...

React: Create a collapsible table to showcase nested JSON data in a structured format

I have a JSON structure that is hierarchical and I am looking to showcase it in a collapsible and nested table format. Is there a React UI framework or plugin that can handle displaying hierarchical data with a slide bar for the "volume" field? And how wou ...

Why isn't my content appearing correctly on different pages?

This ecommerce site is my very first project using React. I have created pages for Contact, Login, and more. The footer and other components display correctly on the home page, but when navigating to other pages, the content appears shortened. For referen ...

What is the best way to enhance the class following this condition in JavaScript?

Initially, the original script worked perfectly with just one class being added: function check_btn_charge() { if (parseInt(jQuery(".total-change-price").text()) >= 0) { jQuery(".btn-action-save-charge"+"&nbsp;"+"btn-danger" ...

The symbiotic partnership between JSF bean and the dynamic capabilities of HTML

As I develop my project in JSF using Primefaces 4.0 and a Tomcat 7 server, I encounter the need to retrieve an image from a MS SQL database and apply clickable areas on it. The coordinates for each area are also obtained from the database. Unfortunately, t ...

JavaScript Age confirmation Overlay

I designed an age verification popup with the help of some online tutorials and a friend due to my limited knowledge of JavaScript. Check it out live here- My issue is that I want this popup to load/appear after the page content loads, but I'm not s ...

Having Trouble Adding a CSS File to Your Django Project? Can't Seem to Get it

I am feeling exhausted trying to solve this problem and now I am in desperate need of help. I have been attempting to add a main.css file to my Django project so that I can handle the CSS myself. I have watched numerous tutorials, but most have crashed m ...

What is the best way to showcase nested array JSON data in an HTML Table?

https://i.stack.imgur.com/OHL0A.png I attempted to access the following link http://jsfiddle.net/jlspake/v2L1ny8r/7/ but without any success. This is my TypeScript code: var viewModel = function(data){ var self = this; self.orders = ko.observableArr ...

Unforeseen issues arise when using material ui's Select component in conjunction with 'redux-form'

I am encountering an issue with a 'redux form' that includes a Select component from the latest material-ui-next. import { TextField } from 'material-ui'; <Field name="name" component={TextField} select > <MenuIte ...

Implement various actions when the window is resized

The carousel code I have found returns a different number of items to display based on screen size. You can check it out here. $(function() { var mini = 1000; var big = 1280; if (window.screen.availWidth < mini) { $('#carousel1').jsCar ...

Tips for preventing DIV elements from overlapping

In the process of creating a CSS design for a SIM game I enjoy playing, a client requested four boxes: two large ones with two smaller ones aligned horizontally in between. Everything was going smoothly until I attempted to add headers to the boxes. The en ...

Update the reference of the 'this' keyword after importing the file

I am currently utilizing react-table to showcase the data. My intention is to house my table columns outside of the react component due to its size and for reusability purposes. I created a table configuration file to contain all of my table configurations ...

Transferring 'properties' to child components and selectively displaying them based on conditions

This is the code for my loginButton, which acts as a wrapper for the Button component in another file. 'use client'; import { useRouter } from 'next/navigation'; import { useTransition } from 'react'; interface LoginButtonPr ...

Tips for Retrieving Html Element Attributes Using AngularJS

Update: Even though the discussion veered off track, the main question still stands - how can I access an attribute of an HTML element within an Angular controller? Check out my attempt on Plnkr: http://plnkr.co/edit/0VMeFAMEnc0XeQWJiLHm?p=preview // ...