Empresas
Empleos
  • Sobre nosotros
  • Soluciones
    • Publicación de vacantes
      Publica tu vacante y recibe candidatos calificados en 48h.
    • Evaluación de candidatos
      500+ pruebas técnicas y psicológicas, más anti-fraude.
    • Headhunting
      Búsqueda ejecutiva a la medida de principio a fin.
    • Nómina + EOR
      Dispersión de nómina y EOR en más de 15 países de LATAM.
  • Precios
  • Empleos

0

181
Vistas
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 Respuestas
Responde la pregunta

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 Denunciar

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 Denunciar

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 Denunciar
Responde la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Comercial
Legal
Términos y condiciones Política de privacidad
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomiéndame algunas ofertas
Necesito ayuda