Handling input fields lets your app listen to what users type and respond to it. This makes your app interactive and useful.
0
0
Handling input fields in React
Introduction
When you want to get user information like name or email.
When you need to update something on the screen as the user types.
When you want to check or validate user input before sending it.
When you want to save user choices or preferences.
When building forms like login, signup, or search boxes.
Syntax
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.
Examples
Basic text input that updates the
name state as you type.React
import React, { useState } from 'react'; const [name, setName] = useState(''); <input type="text" value={name} onChange={e => setName(e.target.value)} />
Email input with an ARIA label for accessibility.
React
import React, { useState } from 'react'; const [email, setEmail] = useState(''); <input type="email" value={email} onChange={e => setEmail(e.target.value)} aria-label="Email address" />
Password input hides typed characters and updates state.
React
import React, { useState } from 'react'; const [password, setPassword] = useState(''); <input type="password" value={password} onChange={e => setPassword(e.target.value)} aria-label="Password" />
Sample Program
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.
React
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> ); }
OutputSuccess
Important Notes
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.
Summary
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.