This is my first React project, so thank you in advance for bearing with me if this is a basic question. I have a two range inputs and I am trying to perform a calculation and update content when those range inputs are moved. Here's my file:
index.tsx
import * as React from 'react'
export default function Index() {
let hours = React.useState(2)
const setHours = (newHours) => {
hours = newHours;
setPrice(hours, price);
}
let miles = React.useState(18)
const setMiles = (newMiles) => {
miles = newMiles;
setPrice(hours, price);
}
let price = React.useState(0)
const setPrice = (hours, miles) => {
price = hours * 6.00 miles * 0.32
}
setPrice(hours, miles);
return (
<div>
<p className="font-medium">Estimated fee of ${price} for a {hours} hour, {miles} mile trip.</p>
<input onChange={(e) => setHours(e.target.value)} value={hours} type="range" min="1" max="24" />
<input onChange={(e) => setMiles(e.target.value)} value={miles} type="range" min="1" max="200" />
</div>
);
}
This unfortunately throws a warning "Functions are not valid as a React child."
CodePudding user response:
that's not how you should use the useState hook in case you want the value you should use the following:
const [hours, setHours] = useState()
then you can use hours as you used it in the example above now you're giving a useState()
hook as the value of your input and that would definitely cause the error you have.
please follow this link to see more about useState
hook
CodePudding user response:
const [hours, setHours] = React.useState(2)
const [miles, setMiles] = React.useState(18)
const [price, setPrice] = React.useState(0)
const handleHours = (newHours) => {
setHours(newHours)
handlePrice()
}
const handleMiles = (newMiles) => {
setMiles(newMiles)
handlePrice()
}
const handlePrice = () => {
let newPrice = hours * 6.00 miles * 0.32;
setPrice(newPrice)
}