Complete the code to create a controlled input field that updates state on change.
import React, { useState } from 'react'; export default function InputExample() { const [value, setValue] = useState(''); return ( <input type="text" value={value} onChange=[1] /> ); }
The onChange handler updates the state with the current input value, making the input controlled.
Complete the code to display the input value below the input field.
import React, { useState } from 'react'; export default function ShowInput() { const [text, setText] = useState(''); return ( <> <input value={text} onChange={(e) => setText(e.target.value)} /> <p>[1]</p> </> ); }
e.target.value outside the event handler.setText instead of the value.The paragraph should display the current state variable text which holds the input's value.
Fix the error in the code to properly update the input state on change.
import React, { useState } from 'react'; export default function FixInput() { const [input, setInput] = useState(''); function handleChange(e) { setInput(e.target.value); } return <input value={input} onChange=[1] />; }
onChange.The handleChange function is passed as the onChange handler. The error is fixed by using setInput(e.target.value) inside the function instead of assignment.
Fill both blanks to create a controlled textarea with placeholder and update state on change.
import React, { useState } from 'react'; export default function TextAreaExample() { const [content, setContent] = useState(''); return ( <textarea placeholder=[1] value={content} onChange=[2] /> ); }
The placeholder attribute shows a hint inside the textarea. The onChange updates the state with the current text.
Fill all three blanks to create a form with controlled inputs for name and age, and handle submit.
import React, { useState } from 'react'; export default function FormExample() { const [name, setName] = useState(''); const [age, setAge] = useState(''); function handleSubmit(e) { e.preventDefault(); alert(`Name: ${name}, Age: ${age}`); } return ( <form onSubmit=[1]> <input type="text" value={name} onChange=[2] placeholder="Name" /> <input type="number" value={age} onChange=[3] placeholder="Age" /> <button type="submit">Submit</button> </form> ); }
The form's onSubmit calls handleSubmit to prevent reload and show alert. The inputs update their respective states on change.