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.