import React from 'react'; export default function LinkComponent() { function handleClick(event) { event.preventDefault(); alert('Link clicked but default prevented'); } return ( <a href="https://example.com" onClick={handleClick} aria-label="Example link"> Go to example.com </a> ); }
The event.preventDefault() stops the browser from following the link. So the alert shows, but navigation does not happen.
import React, { useState } from 'react'; export default function ToggleButton() { const [clicked, setClicked] = useState(false); function handleClick(event) { event.preventDefault(); setClicked(!clicked); } return ( <button onClick={handleClick} aria-pressed={clicked}> {clicked ? 'Clicked!' : 'Click me'} </button> ); }
The handleClick toggles the clicked state. The label updates to 'Clicked!'. The preventDefault() does not stop state changes.
function Form() { function handleSubmit(event) { // prevent form submission } return ( <form onSubmit={handleSubmit} aria-label="Sample form"> <button type="submit">Submit</button> </form> ); }
Only option B correctly receives the event and calls event.preventDefault(). Option B misses the event parameter, causing a ReferenceError. Option B stops propagation but does not prevent submission. Option B returns false but does not prevent default in React.
function MyForm() { function handleSubmit(event) { event.preventDefault(); alert('Form submitted'); } return ( <form onSubmit={handleSubmit} aria-label="Debug form"> <button type="submit">Submit</button> </form> ); }
The handleSubmit function does not receive the event parameter, so event is undefined. This causes a runtime error and prevents preventDefault from working.
event.preventDefault() in event handlers like onClick or onSubmit?event.preventDefault() stops the browser's default behavior like navigating or reloading. This lets React control what happens next without losing state or refreshing the page.