0

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.

1 Answer 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'
>
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.