Categories
React Answers

How to Capture the Last Character of Text Entered with onChange in React?

Spread the love

Sometimes, we want to capture the last character of text entered with onChange in React.

In this article, we’ll look at how to capture the last character of text entered with onChange in React.

Capture the Last Character of Text Entered with onChange in React

To capture the last character of text entered with onChange in React, we can use the useEffect hook to watch for the entered value.

For instance, we can write:

import React, { useEffect, useState } from "react";

export default function App() {
  const [name, setName] = useState("");

  useEffect(() => {
    console.log(name);
  }, [name]);

  return <input onChange={(e) => setName(e.target.value)} />;
}

We set the onChange to a function that calls setName with the e.target.value property, which has the value entered into the input.

Then we watch the name state for changes with the useEffect hook with an array with the name state inside as the 2nd argument.

Then we log the name value in the callback.

The console log should should the whole string that’s been entered

Conclusion

To capture the last character of text entered with onChange in React, we can use the useEffect hook to watch for the entered value.

By John Au-Yeung

Web developer specializing in React, Vue, and front end development.

Leave a Reply

Your email address will not be published. Required fields are marked *