Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to dynamically update the value for any input field with one event handler function, using hooks

TL;DR

Is there any way to dynamically update the value for input fields with one event handler function like we could do with stateful component.

I am working on a login form with 2 fields. Email and Password. When i am using 2 useState representing the two field, then when i update the state with handleChange both state get updated. Which is not the intention.

   const [email, setEmail] = useState()
   const [password, setPassword] = useState()

    const handleChange = e => {
        const {value} = e.target
        setEmail(value)
        setPassword(value)
    }

I don't want to use multiple event handler for handling each input field. I tried this

    const [state , setState] = useState({
        email : "",
        password : ""
    })

    const handleChange = e => {
        const {name , value} = e.target
        setState({
            [name] : value
        })
    }

But this updates one property at a time. And the other property value get lost. So is there any way that i can update all my input fields with one event handler function like we could do with stateful component.

    this.state = {
      email : "",
      password : ""
    }

    const handleChange = e => {
        const {name , value} = e.target
        this.setState({
           [name] : value
        })
    }
like image 806
Rakib Uddin Avatar asked Apr 30 '19 14:04

Rakib Uddin


People also ask

How do you change the input value in React hooks?

Solution: Writing an input with React hooks useInput() will accept an argument called opts , which will allow the developer to pass other input type of properties. Inside useInput() I will create a state hook that will contain the value of the input element and it will be updated onChange event listener .


1 Answers

You should use setState with callback function:

setState(prev => ({ 
    ...prev,
    email: 'new mail',
}))

You'll create a new state object, which was created by previous state. And you can override anything you need. You'd need more new objects if you'd have a complex state object.

like image 137
Doğancan Arabacı Avatar answered Sep 19 '22 15:09

Doğancan Arabacı