Handling input fields lets your app listen to what users type and respond to it. This makes your app interactive and useful.
Handling input fields in React
import React, { useState } from 'react'; const [value, setValue] = useState(''); <input type="text" value={value} onChange={e => setValue(e.target.value)} />
The value attribute links the input to React state.
The onChange event updates the state when the user types.
name state as you type.import React, { useState } from 'react'; const [name, setName] = useState(''); <input type="text" value={name} onChange={e => setName(e.target.value)} />
import React, { useState } from 'react'; const [email, setEmail] = useState(''); <input type="email" value={email} onChange={e => setEmail(e.target.value)} aria-label="Email address" />
import React, { useState } from 'react'; const [password, setPassword] = useState(''); <input type="password" value={password} onChange={e => setPassword(e.target.value)} aria-label="Password" />
This React component shows a text input for your name. As you type, it updates the greeting below in real time. It uses accessible labels and simple styling for clarity.
import React, { useState } from 'react'; export default function NameInput() { const [name, setName] = useState(''); return ( <main style={{ padding: '1rem', fontFamily: 'Arial, sans-serif' }}> <label htmlFor="nameInput" style={{ display: 'block', marginBottom: '0.5rem' }}> Enter your name: </label> <input id="nameInput" type="text" value={name} onChange={e => setName(e.target.value)} aria-label="Name input" style={{ padding: '0.5rem', fontSize: '1rem', width: '100%', maxWidth: '300px' }} /> <p style={{ marginTop: '1rem', fontSize: '1.2rem' }}> Hello, {name || 'stranger'}! </p> </main> ); }
Always link the input's value to state to keep React in control.
Use aria-label or label elements for accessibility.
Remember to handle different input types like text, email, and password properly.
Handling input fields means connecting user typing to React state.
Use value and onChange to keep input and state in sync.
Accessibility and simple styling improve user experience.
Practice
useState when handling input fields in React?Solution
Step 1: Understand the role of useState
useState is a React hook used to create state variables that can hold values and update them.Step 2: Connect useState to input fields
When handling input fields, useState stores the current input value and updates it as the user types.Final Answer:
To store and update the current value of the input field -> Option AQuick Check:
useState manages input value = A [OK]
- Thinking useState styles the input
- Confusing useState with fetching data
- Believing useState stops rendering
Solution
Step 1: Identify the event object usage
The event objectecontains the input element ine.target, and its value is ine.target.value.Step 2: Check the correct syntax for updating state
The state update function should be called withe.target.valueinside the arrow function.Final Answer:
onChange={(e) => setValue(e.target.value)} -> Option BQuick Check:
Use e.target.value to update state [OK]
- Omitting event parameter e
- Using e.value instead of e.target.value
- Passing e.target instead of its value
import React, { useState } from 'react';
function InputExample() {
const [text, setText] = useState('');
return (
<div>
<input value={text} onChange={e => setText(e.target.value)} />
<p>You typed: {text}</p>
</div>
);
}Solution
Step 1: Understand controlled input behavior
The input's value is controlled by the state variabletext. Typing updatestextviasetText.Step 2: Check rendered output
The paragraph displays the currenttextvalue, so typing 'hello' shows 'You typed: hello'.Final Answer:
An input box and a paragraph showing 'You typed: hello' -> Option CQuick Check:
Controlled input shows typed text [OK]
- Thinking input is uncontrolled and won't update
- Expecting paragraph to be empty
- Assuming syntax error without cause
function MyInput() {
const [value, setValue] = useState('');
function handleChange() {
setValue(e.target.value);
}
return <input value={value} onChange={handleChange} />;
}Solution
Step 1: Check the handleChange function signature
handleChange usese.target.valuebut does not receiveeas a parameter, causing a ReferenceError.Step 2: Correct the function to accept event
Addingeas a parameter fixes the error:function handleChange(e) { setValue(e.target.value); }.Final Answer:
The event parameter e is missing in handleChange -> Option AQuick Check:
Event parameter needed in handler [OK]
- Forgetting to add event parameter e
- Using wrong event like onInput
- Removing value prop from controlled input
firstName and lastName, and update their values independently using a single useState object. Which code snippet correctly updates the state when either input changes?const [form, setForm] = useState({ firstName: '', lastName: '' });
// Which onChange handler is correct?
A) onChange={e => setForm({ [e.target.name]: e.target.value })}
B) onChange={e => setForm(prev => ({ ...prev, [e.target.name]: e.target.value }))}
C) onChange={e => setForm({ form, [e.target.name]: e.target.value })}
D) onChange={e => setForm({ form: { [e.target.name]: e.target.value } })}Solution
Step 1: Understand state update with objects
When updating part of an object state, you must merge the new field with existing fields to avoid losing data.Step 2: Analyze each option
Updates state but overwrites other fields, losing data replaces the entire state with only one field, losing the other. Correctly merges new field value with existing state uses a function to merge previous state with the new field correctly. Options C and D incorrectly nest or wrap the state, breaking the structure.Final Answer:
Correctly merges new field value with existing state -> Option DQuick Check:
Use spread operator to merge state updates [OK]
- Overwriting entire state object losing other fields
- Nesting state inside another object accidentally
- Not using functional update form for safety
Ready to prove it?
Pass the test and this pattern moves unknown
