Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

180
Views
How to Change Button text in React using useState

I have a button with Text Click View Price. I am displaying Amount when button is clicked.

I want to change the button value to priceVar = "Reset Price"; which is not happening in my case. I am able to set value to 0.

How can I set button text to Reset Price again?

 const [price, setPrice] = useState(0);
  let priceVar = "Click View Price";
  const viewPrice = () => {
    if (price === 0) {
      setPrice(Math.floor(Math.random() * 100));
    } else {
      priceVar = "Reset Price"; --------------------> NOT WORKING
      setPrice(0);
    }
  };

  return (
    <article
      className="book"
      onMouseOver={() => {
        console.log(title);
      }}
    >
      <div>
        <button type="button" onClick={viewPrice()}>
          {priceVar}
        </button>
        <h3>${price}</h3>
      </div>
    </article>
  );
about 4 years ago · Juan Pablo Isaza
3 answers
Answer question

0

You can create useState hook for Button text as below

 const [priceVar, setpriceVar] = useState("Click View Price");

 const viewPrice = () => {
    if (price === 0) {
      setpriceVar("Click View Price");
      setPrice(Math.floor(Math.random() * 100));
    } else {
      setpriceVar("Reset Price");
      setPrice(0);
    }
  };
about 4 years ago · Juan Pablo Isaza Report

0

Your variable is not React State!

import { useState } from "react";

let priceVar = "...";
// Try useState like with your price variable:

const [priceVarNew, setPriceVarNew] = useState("Click View Price")
// Then reference that state like your price with:  {priceVar}, or change it accordingly with setState("Reset Price")

about 4 years ago · Juan Pablo Isaza Report

0

You can also make ternary for this one also.

setPrice(price === 0 ? Math.floor(Math.random() * 100) : 0);

about 4 years ago · Juan Pablo Isaza Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!