Complete the code to add a click event handler to the button.
function ClickButton() {
function handleClick() {
alert('Button clicked!');
}
return <button onClick=[1]>Click me</button>;
}The onClick attribute expects a function reference, so you pass handleClick without parentheses.
Complete the code to update the state when the button is clicked.
import { useState } from 'react'; function Counter() { const [count, setCount] = useState(0); function increment() { setCount([1]); } return <button onClick={increment}>Count: {count}</button>; }
count++ which does not work as expected in React state.setCount + 1 which is invalid.To update the state, you pass the new value to setCount. Here, we add 1 to the current count.
Fix the error in the event handler to prevent the default form submission.
function Form() {
function handleSubmit(event) {
[1];
alert('Form submitted!');
}
return (
<form onSubmit={handleSubmit}>
<button type="submit">Submit</button>
</form>
);
}prevent() or defaultPrevented().stopPropagation() which only stops event bubbling.Calling event.preventDefault() stops the form from submitting and refreshing the page.
Fill both blanks to create a button that toggles text between 'ON' and 'OFF'.
import { useState } from 'react'; function ToggleButton() { const [isOn, setIsOn] = useState(false); function toggle() { setIsOn([1]); } return <button onClick={toggle}>{isOn ? [2] : 'OFF'}</button>; }
isOn which does not toggle.We toggle the boolean state by setting it to !isOn. The button shows 'ON' when isOn is true.
Fill all three blanks to create a form input that updates state and shows the typed text.
import { useState } from 'react'; function TextInput() { const [text, setText] = useState(''); function handleChange(event) { setText([1]); } return ( <> <input type="text" value={text} onChange=[2] aria-label=[3] /> <p>You typed: {text}</p> </> ); }
text instead of event.target.value to setText.aria-label for accessibility.The input's onChange calls handleChange. Inside it, we update state with event.target.value. The aria-label improves accessibility by describing the input.