Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

182
Visualizações
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 Respostas
Responde à pergunta

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 Relatório

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 Relatório

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 Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda