1

I got two inputs. If I want to bind the input value with a state variable, I use this -

The state :

 const [message, setMessage] = useState('')
 const [newUser, setNewUser] = useState('')

The methods the bind them :

 const handleMessageChange = (e) => setMessage(e.target.value)
 const handleUserChange = (e) => setNewUser(e.target.value)

And I call these methods with the onChange property on the input.

My qusetion :

Can I use a generic handleChange method instead of explicitly creating a method to each input/state pair? If so, how?

apollo24
  • 303
  • 4
  • 16

2 Answers2

3

Here's 2 ways to do so: https://codesandbox.io/s/relaxed-pine-zgwfy

Illustrating one of the ways here.

The hooks and handler:

const [message, setMessage] = useState("");
const [newUser, setNewUser] = useState("");
const handleChange = e =>
    e.target.name === "message"
        ? setMessage(e.target.value)
        : e.target.name === "user"
        ? setNewUser(e.target.value)
        : "";

The inputs:

<input name="message" value={message} onChange={handleChange} />
<input name="user" value={newUser} onChange={handleChange} />

Hope that helps,

Cheers!

Raz Chiriac
  • 406
  • 2
  • 7
3

You might consider store both user and message in one {data} state holder, and at handleChange modified just the relevant key in state object


  const [data, setData] = useState({user: "", message: ""})

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

  <input name="message" value={data.message} onChange={e => handleChange(e)} />
  <input name="user" value={data.user} onChange={e => handleChange(e)} />

Hagai Harari
  • 2,767
  • 3
  • 11
  • 23