What is the best way to alter the state of a button when it is clicked in React, and then return it to its original state when

I'm working on a button that I've defined like this:

<button className={class} onClick={() => changeClassProperty()}>
        {classText}
</button>

My goal is to update both the CSS styling class and the text of the button A when it's clicked. Currently, I'm using the UseState hook in the following way:

const [classColor, setClassColor] = useState(styles.classAButton);
const [classText, setClassText] = useState("A");

The handler changeClassColor() is responsible for updating the CSS color style and the text of my button like this:

function changeClassProperty() {
    setClassColor(styles.classBButton);
    setClassText("B");
  }

So, clicking on button A changes its color and text to button B. Now, I want to toggle between states A and B with each click. How can I achieve this?

Answer №1

If you want to reference the previous state in setState, you can do so by using an arrow function.

setClassText(prevState => prevState === "A" ? "B" : "A");

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

Aligning the anchor element to the right inside a div is not functioning as expected

I've been working on creating a sidebar with an 'X' button in the top right corner. Initially, I attempted to use float: right to position it on the right side, but unfortunately, this didn't produce the desired result. The anchor tag ...

Having trouble sending data to a Laravel 5 controller through Angular. Keep getting Error 422: Unprocessable Entity

My login form is built with angularjs, and I am trying to send the user's credentials to the default AuthController in Laravel 5. However, I keep encountering a server response of 422 Unprocessable Entity with the message: email field is required. HT ...

Axios is returning a 401 (Unauthorized) error when attempting to retrieve user data from a React frontend and pass it to DRF Social Oauth2. Strangely, the same process

Here are the contents of two files, LoginScreen.JS and login.JS. The LoginScreen.JS file contains a submit handler that submits user input, while we import the axios instance from login.JS. In addition, a working example from PostMan has been provided. lo ...

Problems with Navbar rendering on multiple occasions

GENERAL INFO I've encountered an issue with the re-rendering of my sidemenu in Gatsby. Despite my efforts, I can't prevent the sidemenu from re-rendering and overriding the data that I set for it. const [activeParent, setActiveParent] = useState ...

Having trouble loading JSON api data in React?

Recently, I've delved into the world of React and was assigned a task to fetch data from a JSON API and showcase it on the screen. Initially, everything went smoothly while practicing with this URL - https://jsonplaceholder.typicode.com/users. Howeve ...

React Apollo Error: There are no additional mocked responses available for the specified query mutation

Purpose: MockedProvider should mimic the createPost mutation. Current Situation: Error: No additional mocked responses available for the query: mutation... Steps to Reproduce the Problem: I have a very basic repository. Additionally, I have cre ...

Prevent the ReactJS submit button from being activated if the text area contains any missp

I've been working with ReactJS and recently designed a form. One of the requirements is to disable the send button if the text area in the form contains spelling errors. I attempted using a spell check feature, however, it only underlines the errors ...

Is there a way to adjust the pivot point of the object's rotation?

I have incorporated a 3D hamburger model on my website using Three.js. However, I am facing an issue where the rotation behaves unexpectedly. The burger is supposed to rotate around itself at a 45-degree angle, but instead, it rotates from the upper left c ...

What are the best ways to integrate jQuery into a React application?

I am in the process of developing a responsive menu for my react app, but I'm facing some challenges as a newcomer to react. In order to achieve the desired functionality, I am trying to incorporate jQuery for menu toggling. However, when I attempt to ...

Issue with ui-sref functionality in Ionicview, functioning properly on browser, device, and emulator

My development process involves using ionic to create an application. While most of the links work without any issues, I have encountered a specific problem with one list in ionicview. The HTML code for this particular list is as follows: <ion-list ...

Passing a boolean as the value for a Material UI MenuItem in a React TypeScript application

I am encountering an issue as a beginner in react with passing a simple boolean value as a prop for the MenuItem component in the material UI library. I believe the solution is not too complex. Can someone provide guidance on how to fix this error? The sp ...

Is there a way to modify the value of an object in a Vuex store using actions in Vue.js?

I have data stored in an array within the state and I need to update a specific object. How can I change the value of the object with id 1 to true using Vuex actions? state.js const array=[] mutations.js storeArray(state, data) { state.array = data ...

Form duplicates messages sent

I have made some adjustments to a free form, and it seems to be functioning properly. However, I have encountered an issue where the email is being sent twice and the message is written twice after completion. I attempted to replace the button and input ...

Having trouble with your contact form and not getting it to work properly with Javascript, Ajax, or

I've been struggling to get a contact form working for an entire day. I included the following script at the top of my page: <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.0/jquery.min.js"></script> This is the structure ...

Using Jasmine to simulate multiple method calls in a testing environment

Currently, I am working on writing a JavaScript test for a method that involves making two function calls (model.expandChildren() and view.update();). // within the 'app' / 'RV.graph' var expandChildren = function(){ return model.e ...

Is this the correct method for constructing a class in CSS?

What is the correct way to style a class with CSS and write HTML code? .first{ color:red; } Here is an example of HTML code: <class id=first> <p> some text </p> <p> some other text </p> ...

React Materialize not displaying properly

I am trying to integrate Materialize modal into my React project, but I am facing an issue where the modal does not display anything. I have split the modal into its own component and the button that triggers the modal is located in the parent container. ...

Tips for building an API using an app router in Next.js

After setting up my new project and using the app router as recommended in the latest version of Next.js, I am now looking to create an API. How can I go about creating and utilizing this API within my page app/user/page.tsx? I have already created an API ...

"amCharts Version 4 introduces a new feature allowing for the month format to be displayed on the Date

When setting up my XYChart, I am facing an issue with the x-Axis labels. I want to display the twelve months from Jan to Dec, but in the image provided, the first month is also showing the Year (yyyy) along with it. let dateAxis = chart.xAxes.push(new ...

Unusual glitch found in React/Redux component leading to unexpected redirection?

When you click on a list of products on the home screen, it navigates to the product screen page displaying one product along with its details. However, after adding onClick and onChange handlers to the button and quantity select in productScreen.js, I not ...