How to Copy a Value From One Input Field to Another "onBlur" in React?

To copy value from one input field to another in React, when the first input field loses focus (i.e. on the blur event), you can follow these steps:

  1. Create a state variable within your component's state to store the value of the input field you want to copy;
  2. Use the useRef() hook to create a reference for the second input field (which will be used to assign the value from the first input field);
  3. Implement an onChange event handler for the first input field to update the state variable with its current value;
  4. Add an onBlur event handler for the first input field to assign its value from the state variable to the value of the second input field.

The reason for using the useRef() hook for the second input field is to avoid triggering an unnecessary re-render of the component. If you were to use the useState() hook for it instead, any change to its value would cause a re-render of the component. This behavior can be useful when there are other components or values that rely on the value of the second input field.

For example, you can implement the steps mentioned above in the following way:

import React, { useState, useRef } from 'react';

function App() {
  const [inputValue, setInputValue] = useState('');
  const secondInput = useRef(null);

  const handleInputChange = (event) => {
    setInputValue(event.target.value);
  };

  const handleInputBlur = () => {
    secondInput.current.value = inputValue;
  };

  return (
    <div>
      <input
        type="text"
        value={inputValue}
        onChange={handleInputChange}
        onBlur={handleInputBlur}
      />

      <input ref={secondInput} type="text" />
    </div>
  );
}

export default App;

By following these steps, the first input field's value will be copied to the second input field when the first field loses focus.


This post was published (and was last revised ) by Daniyal Hamid. Daniyal currently works as the Head of Engineering in Germany and has 20+ years of experience in software engineering, design and marketing. Please show your love and support by sharing this post.