Complete the code to add a click event handler that updates the count state.
import React, { useState } from 'react'; export default function Counter() { const [count, setCount] = useState(0); return ( <button onClick=[1]> Count: {count} </button> ); }
The onClick event handler needs a function that calls setCount to update the state. Using an arrow function () => setCount(count + 1) ensures the function runs only when clicked.
Complete the code to prevent the default form submission behavior in the event handler.
export default function Form() {
function handleSubmit(event) {
[1];
alert('Form submitted!');
}
return (
<form onSubmit={handleSubmit}>
<button type="submit">Submit</button>
</form>
);
}To stop the form from refreshing the page on submit, call event.preventDefault() inside the handler.
Fix the error in the event handler to correctly update the state with the previous count value.
import React, { useState } from 'react'; export default function Counter() { const [count, setCount] = useState(0); function increment() { setCount([1]); } return <button onClick={increment}>Count: {count}</button>; }
Using the updater function prev => prev + 1 ensures the state updates correctly even if multiple updates happen quickly.
Fill both blanks to create a button that toggles between 'ON' and 'OFF' states.
import React, { useState } from 'react'; export default function Toggle() { const [isOn, setIsOn] = useState(false); return ( <button onClick=[1]> [2] ? 'ON' : 'OFF' </button> ); }
The onClick handler toggles the boolean state by negating the previous value. The button text shows 'ON' if isOn is true, otherwise 'OFF'.
Fill all three blanks to create a controlled input that updates its value on change.
import React, { useState } from 'react'; export default function TextInput() { const [text, setText] = useState(''); function handleChange(event) { [1](event.[2].[3]); } return <input type="text" value={text} onChange={handleChange} aria-label="Text input" />; }
The handleChange function updates the state with the current input value from event.target.value by calling setText.