how to pass textbox target value onchange event and change object properties using hooks

Viewed 40

to update the complete object properties by using useState

pass textbox target value onchange event and change object properties using hooks

function ExampleObjectHooks() {

    const [name, setname] = useState({ first: '', last: '' });

    const onInputNameChange = (e) => {
        setname({ first: e.target.value, last: e.target.value });
        console.log(name);
    }


    return (
        <div>
            <form>
                <input type="text" onChange={(e) => onInputNameChange(e)} ></input>
                <input type="text" onChange={e => onInputNameChange(e)} ></input>
            </form>
            {name.first}{name.last}
        </div>
    );
}
1 Answers

Add an name attribute to each input field, and update the state using the name (key in the code). Node that you need to merge the state of each field by yourself. To so spread the previous state, and override the field you've just updated.

const { useState } = React;

function ExampleObjectHooks() {

  const [name, setname] = useState({ first: '', last: '' });

  const onInputNameChange = ({ target }) => {
    const { name: key, value } = target;
    
    setname(state => ({
      ...state,
      [key]: value
    }));
  };

  return (
    <div>
      <form>
        <input name="first" type="text" onChange={onInputNameChange} ></input>
        <input name="last" type="text" onChange={onInputNameChange} ></input>
      </form>
      {name.first} {name.last}
    </div>
  );
}

ReactDOM.render(
  <ExampleObjectHooks />,
  root
);
<script crossorigin src="https://unpkg.com/react@17/umd/react.development.js"></script>
<script crossorigin src="https://unpkg.com/react-dom@17/umd/react-dom.development.js"></script>

<div id="root"></div>

Related