Complete the code to handle a click event on the button.
function ClickButton() {
function handleClick() {
alert('Button clicked!');
}
return <button onClick={handleClick}>Click me</button>;
}The onClick attribute expects a function reference, so you pass handleClick without parentheses.
Complete the code to access the event object in the click handler.
function ClickLogger() {
function handleClick([1]) {
console.log([1].type);
}
return <button onClick={handleClick}>Log Event</button>;
}The event object is commonly named e or event. Here, e is used as the parameter to access event properties.
Fix the error in the code to prevent the default form submission behavior.
function FormSubmit() {
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 update state with the input value on change.
import { useState } from 'react'; function TextInput() { const [text, setText] = useState(''); function handleChange([1]) { setText([2].target.value); } return <input type="text" value={text} onChange={handleChange} aria-label="Text input" />; }
The event object is commonly named e. We use e.target.value to get the input's current value.
Fill all three blanks to create a button that toggles a message on click using state and synthetic events.
import { useState } from 'react'; function ToggleMessage() { const [visible, setVisible] = useState(false); function handleClick([1]) { setVisible(prev => ![2]); } return ( <> <button onClick=[3] aria-pressed={visible} aria-label="Toggle message"> Toggle Message </button> {visible && <p>The message is now visible.</p>} </> ); }
The event parameter is named e. We toggle the visible state by negating it. The button's onClick uses the handleClick function.