Imperatively Selecting Text
What you'll learn: How to programmatically highlight all text in an input field using a ref, making it easy for users to copy or replace content.
Sometimes you want to automatically select (highlight) all the text in an input field—perhaps when a user clicks a "copy" button or when a field becomes active. With uncontrolled components and refs, you can do this imperatively using the DOM's built-in .select() method.
The Core Technique
Once you have a ref attached to an input element, you can call inputRef.current.select() to highlight all the text inside it:
import { useRef } from 'react';
function CopyableInput() {
const inputRef = useRef(null);
function handleSelectAll() {
inputRef.current.select();
}
return (
<div>
<input
ref={inputRef}
defaultValue="Copy me!"
type="text"
/>
<button onClick={handleSelectAll}>
Select All
</button>
</div>
);
}
When the button is clicked, all text in the input becomes highlighted—just like when you press Ctrl+A (or Cmd+A). This makes it trivial for users to copy the value.
Common Use Cases
- "Copy to clipboard" workflows: Select text before copying
- Edit mode: Auto-select existing text so users can quickly replace it
- Confirmation codes: Highlight tokens for easy copying
Why This Matters
The .select() method is a standard DOM API that works on text inputs and textareas. By combining it with refs, you get precise, imperative control over user interaction without needing to manage the input's value through state.
Key Takeaway: Use inputRef.current.select() to programmatically highlight all text in an input, creating user-friendly copy and edit interactions.