Home > database >  How to make an input of type number a controlled component in react
How to make an input of type number a controlled component in react

Time:12-09

export default function Form() {
const [user, setUser] = useState({
    name: "",
    numOfQs: 0
})
console.log(user)
function handleUserDataChange(event) {
    setUser(prevUser => {
        return {
            ...prevUser,
            [event.target.name]: event.target.value
        }
    })
}
return (
    <>
        <input 
        type="text" 
        placeholder="username"
        name="name"
        value={user.name}
        onChange={handleUserDataChange} />
        <input 
        type="number" 
        name="numOfQs"
        value={user.numOfQs}
        onChange={handleUserDataChange} />
    </>
)}

I was trying to build my form using react, and when I tried to use input[type: number] on the form field it was giving me this error, don't know why. I was reading through react docs about forms, and everything from the checkbox, radio buttons, textarea was all working fine. but when I used an input element of the type number, I got the following error.

*!Warning: This synthetic event is reused for performance reasons. If you're seeing this, you're accessing the property target on a released/nullified synthetic event. This is set to null. If you must keep the original synthetic event around, use event.persist(). See fb.me/react-event-pooling for more information.

so, the problem only arises when an input of type "number" is introduced. when I remove it all of my other form elements work fine.

I'm still in the learning phase of react. please help me out.

CodePudding user response:

This happened because the event that passed into the function is used as an asynchronous event.

To fix this, decompose the event object

function handleUserDataChange(event) {

    const { name, value } = event.target;
    setUser(prevUser => {
        return {
            ...prevUser,
            [name]: value
        }
    })
}
  • Related