apollo24
apollo24

Reputation: 313

Two way binding more than one input in React w/ Hooks

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?

Upvotes: 2

Views: 2702

Answers (2)

Hagai Harari
Hagai Harari

Reputation: 2877

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 = useCallback((e) => setData((prev) => ({ ...prev, [e.target.name]: e.target.value })), []);

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

Upvotes: 5

Raz Chiriac
Raz Chiriac

Reputation: 416

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! 🍻

Upvotes: 3

Related Questions