'how to update react hooks array state?
I have react-hooks with array state. I would like to update my date data from this code.
const [[birthYear, birthMonth, birthDay], setStudentDob] = useState([]);
how can I change with the OnChange event on reacts?
//date
<select
value={birthDay}
onChange={handelDate}
name='day'
>
<option value='0'>Day</option>
<option value='01'>01</option>
<option value='02'>02</option>
<option value='03'>03</option>
</select>
//birthMonth
<select
value={birthMonth}
onChange={handelDate}
name='month'
>
<option value='0'>Day</option>
<option value='01'>january</option>
<option value='02'>february</option>
<option value='03'>march</option>
</select>
</select>
//birthYear
<select
value={birthYear}
onChange={handelDate}
name='year'
>
<option value='0'>Day</option>
<option value='2020'>2020</option>
<option value='2021'>2021</option>
<option value='2020'>2022</option>
</select>
if you have any preferable way to update please help me to find out these issues.
Solution 1:[1]
The handleDate can be like this:
const handleDate = (value, index) => {
setStudentDob(s => {
let arr = [...s];
arr[index] = value;
return arr;
})
}
Make sure to pass the correct parameters in the onChange handler:
<select
value={birthDay}
onChange={e => handleDate(e.target.value, 2)}
name='day'
>
<select
value={birthMonth}
onChange={e => handleDate(e.target.value, 1)}
name='month'
>
<select
value={birthYear}
onChange={e => handleDate(e.target.value, 0)}
name='year'
>
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | Hakim Abdelcadir |
