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>
);
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);
}
};
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")
You can also make ternary for this one also.
setPrice(price === 0 ? Math.floor(Math.random() * 100) : 0);