Consider this React component that uses a controlled input. What will be displayed when the user types 'hello'?
import React, { useState } from 'react'; function ControlledInput() { const [text, setText] = useState(''); return ( <div> <input type="text" value={text} onChange={e => setText(e.target.value)} aria-label="input-text" /> <p>{text}</p> </div> ); } export default ControlledInput;
Think about how the state updates on input change and how it affects the paragraph.
The component uses a controlled input where the input's value is tied to the state variable text. When the user types, onChange updates text, which then updates the paragraph content. So the paragraph shows exactly what the user types.
Given this controlled component, what will be the value of name state after the user types 'React'?
import React, { useState } from 'react'; function NameInput() { const [name, setName] = useState(''); function handleChange(e) { setName(e.target.value.toUpperCase()); } return <input type="text" value={name} onChange={handleChange} aria-label="name-input" />; } export default NameInput;
Look at how the input value is transformed before setting state.
The handleChange function converts the input value to uppercase before setting the state. So typing 'React' results in state being 'REACT'.
Identify which code snippet will cause a syntax error when used as a controlled input in React.
Check the JSX syntax carefully, especially the closing of the input tag.
Option A has an incorrect closing of the input tag: / > instead of />. This causes a syntax error in JSX.
Look at this React component. Why does the input not show any typed characters?
import React, { useState } from 'react'; function BrokenInput() { const [text, setText] = useState(''); return <input type="text" value={text} onChange={() => setText('')} aria-label="broken-input" />; } export default BrokenInput;
Check what the onChange function does to the state.
The onChange handler sets the state to an empty string every time the input changes. This means the input value is always reset to empty, so the user cannot type anything visible.
Why do React developers prefer controlled components for form inputs?
Think about how controlled components relate to React state and UI updates.
Controlled components keep the form data in React state, making it easy to validate input, conditionally render UI, and keep data consistent. They do not inherently optimize performance or reduce code length.