Home > OS >  how to update react hooks array state?
how to update react hooks array state?

Time:04-28

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.

CodePudding user response:

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'
>
  • Related