Ask Your Question

Revision history [back]

click to hide/show revision 1
initial version

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.