How to update a React input text field with the value on onBlur event?

Sometimes, we want to update a React input text field with the value on onBlur event.

In this article, we’ll look at how to update a React input text field with the value on onBlur event.

How to update a React input text field with the value on onBlur event?

To update a React input text field with the value on onBlur event, we can set the onBlur prop of the input to a function that does something with the input value.

For instance, we write:

import React, { useState } from "react";

export default function App() {
  const [inputValue, setInputValue] = useState("");

  const handleChange = (e) => {
    setInputValue(e.target.value);
  };

  const updateInput = () => {
    console.log(inputValue);
  };

  return (
    <div>
      <input value={inputValue} onChange={handleChange} onBlur={updateInput} />
    </div>
  );
}

We defined the inputValue state with the useState hook.

Then we set the value prop of the input to inputValue.

And we set the onChange prop to handleChange to set inputValue to the value of the input with setInputValue.

Next, we set the onBlur prop to updateInput to log the value of inputValue when we move focus away from the input.

Conclusion

To update a React input text field with the value on onBlur event, we can set the onBlur prop of the input to a function that does something with the input value.