Accessing Input Values: event.target.value
What you'll learn: How to retrieve the current text from an input field using the onChange event's target.value property.
The Core Idea
When you attach an onChange handler to an input element, React calls that function every time the user types or changes the input. The event object passed to your handler contains a target property (the input element itself), which has a value property representing the current text in that input.
Think of event.target as a reference to the actual input box on the page, and value as reading what's currently written inside it.
How It Works
function MyInput() {
const handleChange = (event) => {
console.log(event.target.value); // Logs current input text
};
return <input type="text" onChange={handleChange} />;
}
Every keystroke triggers onChange, and event.target.value gives you the complete, updated text after that keystroke. If the user types "hello" one letter at a time, you'll see:
- "h"
- "he"
- "hel"
- "hell"
- "hello"
Connecting to State
This is how controlled components work with useState:
function ControlledInput() {
const [text, setText] = useState('');
const handleChange = (event) => {
setText(event.target.value); // Store the input's value in state
};
return <input type="text" value={text} onChange={handleChange} />;
}
You grab event.target.value and pass it to your state setter. Now the input's value is controlled by React state.
Key Takeaway: event.target.value is how you read the current input text from the onChange event—it's the bridge between user typing and your React state updates.