When I run this code it will just repeat doing window prompt "what currency do you use?", even once I enter a valid currency. I'm very new to js and react so sorry if this is really simple
import React from "react"
function Product(props) {
const MoreInfo = () => {
alert(props.product.description);
}
const UserCurrency = window.prompt("What currency do you use?")
var formatter = new Intl.NumberFormat('en-US', {
style: 'currency',
currency: UserCurrency,
})
return (
<div>
<h2>{props.product.name}</h2>
<p>{formatter.format(props.product.price)}</p>
<button onClick={MoreInfo}>More Info</button>
</div>
)
}
export default Product
CodePudding user response:
You need to learn about react hooks, in this case: useState and useEffect
import { useState, useEffect } from 'react'
function Product(props) {
const [userCurrency, setUserCurrency] = useState(null)
useEffect(() => {
const uc = window.prompt("What currency do you use?")
setUserCurrency(uc)
}, [])
const MoreInfo = () => {
alert(props.product.description);
}
var formatter = new Intl.NumberFormat('en-US', {
style: 'currency',
currency: UserCurrency,
})
return (
<div>
<h2>{props.product.name}</h2>
<p>{formatter.format(props.product.price)}</p>
<button onClick={MoreInfo}>More Info</button>
</div>
)
}
export default Product
with useEffect, the code will run only once when the component is mounted, if you pass an empty array of dependencies as a second argument.
Please read the docs, as this explanation is far from enough to understand what's at stake here