🚨 CODE DUPLICATION 🚨
So I am trying to have an inital state object like: {prop1: val1, prop2: val2}
and get seperate values from two <selection>
fields.
I am having problems with getting each event.target.value
on submit.
The only solution I came up with is splitting the original state into different objects, duplicate the handler functions and merge them on submit. But as you can see this is getting ugly pretty quick, I am sure that this could be optimized but I am getting nowhere with the unique event handlers.
const [firstSelection, setFirstSelection] = useState({color: 'green'})
const [secondSelection, setSecondSelection] = useState({time: 'evening'})
const handleFirstChange = e => setFirstSelection({ color: e.target.value })
const handleSecondChange = e => setSecondSelection({ time: e.target.value })
const getSelection = e => {
e.preventDefault()
console.log({...firstSelection, ...secondSelection})
}
const Form = () => {
return (
<form>
<div className='selectWrapper'>
<select name='color' value={firstSelection.color} onChange={handleFirstChange}>
<option value='red'>Red</option>
<option value='blue'>Blue</option>
<option value='yellow'>Yellow</option>
<option value='green'>Green</option>
</select>
</div>
<div className='selectWrapper'>
<select name='time' value={secondSelection.time} onChange={handleSecondChange}>
<option value='morning'>Morning</option>
<option value='evening'>Evening</option>
<option value='night'>Night</option>
</select>
</div>
<input type='submit' value='Submit' onClick={getSelection}/>
</form>
)
}
Try this :
export default function Form() {
const [selection, setSelection] = useState({ color: "red", time: "morning" });
const handleChange = (e) => {
setSelection({ ...selection, [e.target.name]: e.target.value });
};
const getSelection = (e) => {
e.preventDefault();
console.log(selection);
};
return (
<form>
<div className="selectWrapper">
<select
name="color"
value={selection.color}
onChange={(e) => handleChange(e)}
>
<option value="red">Red</option>
<option value="blue">Blue</option>
<option value="yellow">Yellow</option>
<option value="green">Green</option>
</select>
</div>
<div className="selectWrapper">
<select
name="time"
value={selection.time}
onChange={(e) => handleChange(e)}
>
<option value="morning">Morning</option>
<option value="evening">Evening</option>
<option value="night">Night</option>
</select>
</div>
<input type="submit" value="Submit" onClick={getSelection} />
</form>
);
}