In my component I have input range which have 5 values and for each there is price assign. I also have input checkbox with which I want to apply extra discount. So when it is set to true I want to use discount. Should I write another function or maybe I can use one of the functions I have already written?
const Cost = () => {
const arr = data.map(arr => arr)//here I have array with data like {"range": 3,"views": 100,"price":16
},
const [value, setValue] = useState(arr[2])//default value for range
const [checked, setChecked] = useState(false)//default value for checkbox
function handleChangeValue(e) {
setValue(arr[e.target.value - 1])
}//changing price when range is changed
function toggleChange() {
setChecked(prev => !prev)
}//changing checkbox
return (
<>
<Views>{value.views} pageviews</Views>
<Input
value={value.range}
onChange={handleChangeValue}
type="range"
name="range"
min="1"
max="5"
list="views">
</Input>
<Price><span>${value.price}</span>/month</Price>//this is price which I want to change
<Switch onClick={toggleChange} >
<label className="switch" htmlFor="toggle">
<input name="toggle" type="checkbox" aria-label="toggle" checked={checked} />//when this is set to true I want to apply extra 25% discount to my price
<span className="slider"></span>
</label>
</Switch>
</>
)
}
At first I wanted to create two different components for those inputs but wasn't sure how I could have change the price then.
To sum up - price is changed when range is changed and when checkbox is true. Can you guys advise?
UPDATE
const [newPrice, setNewPrice] = useState(arr[2].price);
useEffect(() => {
let newPrice = value.price
if (checked) {
newPrice -= 0.25 * newPrice;
} else {
return newPrice
}
setNewPrice(newPrice)
}, [value, checked])
It does apply discount when I set checkbox to true but when I am switching it back to false, price is still with discount.