Categories
React Answers

How to select all text in input with React when it focused?

Spread the love

Sometimes, we want to select all text in input with React when it focused.

In this article, we’ll look at how to select all text in input with React when it focused.

How to select all text in input with React when it focused?

To select all text in input with React when it focused, we can call select on the input element to select the input value when the element is in focus.

For instance, we write

const Comp = () => {
  //...
  const inputEl = useRef(null);

  const handleFocus = () => {
    inputEl.current.select();
  };

  <input
    type="number"
    value={quantity}
    ref={inputEl}
    onChange={(e) => setQuantityHandler(e.target.value)}
    onFocus={handleFocus}
  />;
};

to assign the inputEl ref to the input.

Then we set the onFocus prop to the handleFocus function, which runs when we focus on the input.

In handleFocus, we call inputEl.current.select to select all the input value text in the input box.

Conclusion

To select all text in input with React when it focused, we can call select on the input element to select the input value when the element is in focus.

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 *