One approach to addressing the issue of combining two items into a single value in React implementation is to use an array or an object to store the values of the two items.
For example, if you want to combine a first name and a last name into a single value, you could create an object with properties for first name and last name, and then use that object as the value of a form input:
import React, { useState } from 'react';
function NameInput() {
const [name, setName] = useState({ firstName: '', lastName: '' });
const handleChange = (event) => {
const { name: fieldName, value } = event.target;
setName((prevName) => ({ ...prevName, [fieldName]: value }));
};
return (
<form>
<label>
First Name:
<input
type="text"
name="firstName"
value={name.firstName}
onChange={handleChange}
/>
</label>
<label>
Last Name:
<input
type="text"
name="lastName"
value={name.lastName}
onChange={handleChange}
/>
</label>
<p>Your full name is {name.firstName} {name.lastName}.</p>
</form>
);
}
In this example, the state name
is an object with properties for firstName
and lastName
. The handleChange
function updates the name
state whenever one of the input fields is changed. The full name is then displayed using string interpolation of the firstName
and lastName
properties.
This approach can be extended to more complex use cases, such as combining multiple values into a single object or array.
Asked: 2022-02-11 11:00:00 +0000
Seen: 1 times
Last updated: Aug 27 '22