I have a form in react with couple of fields. 2 of those should be connected... If you enter 1, the other should be updated accordingly, but I can't get the hang of it. Whatever I try, handleChange updates only 1...
const [form, setForm] = useState({
name: "",
nameEng: "",
type: "",
priceKN: "",
priceEUR: "",
});
const handleChange = (event) => {
setForm({ ...form, [event.target.name]: event.target.value });
};
...
<input
type="number"
name="priceKN"
value={form.priceKN}
onChange={handleChange}
></input>
<input
type="number"
name="priceEUR"
value={form.priceEUR}
onChange={handleChange}
></input>
So, when you enter for example 1st value, 2nd should be calculated (priceKN / 7.54) and vice versa, and shown in the form, but it's not working. Any help would be appreciated
CodePudding user response:
Parego, it happen because you update the fields in dynamically way. you need to do this way:
const [form, setForm] = useState({
name: "",
nameEng: "",
type: "",
priceKN: "",
priceEUR: "",
});
const specials = ['priceKN',]
const handleChange = (event) => {
if(event.target.name == 'priceKN' || event.target.name == 'priceEUR')
setForm({ ...form, priceKN: event.target.value,priceEUR: event.target.value});
else
setForm({ ...form, [event.target.name]: event.target.value });
};
...
<input
type="number"
name="priceKN"
value={form.priceKN}
onChange={handleChange}
></input>
<input
type="number"
name="priceEUR"
value={form.priceEUR}
onChange={handleChange}
></input>
CodePudding user response:
Create a function (getValues
in the example) that parses the input, and creates an object that you can spread on the current form values:
const { useState } = React;
const getValues = ({ name, value, valueAsNumber }) => {
switch(name) {
case 'priceKN':
return {
priceKN: valueAsNumber,
priceEUR: valueAsNumber * 0.13
};
case 'priceEUR':
return {
priceKN: valueAsNumber * 7.53,
priceEUR: valueAsNumber
};
default:
return { [name]: value };
}
}
const Demo = () => {
const [form, setForm] = useState({
name: "",
nameEng: "",
type: "",
priceKN: 0,
priceEUR: 0,
});
const handleChange = event => {
setForm(values => ({
...values,
...getValues(event.target)
}));
};
return (
<div>
<input
type="number"
name="priceKN"
value={form.priceKN}
onChange={handleChange}
></input>
<input
type="number"
name="priceEUR"
value={form.priceEUR}
onChange={handleChange}
></input>
</div>
);
}
ReactDOM
.createRoot(root)
.render(<Demo />);
<script crossorigin src="https://unpkg.com/react@18/umd/react.development.js"></script>
<script crossorigin src="https://unpkg.com/react-dom@18/umd/react-dom.development.js"></script>
<div id="root"></div>