Command Palette

Search for a command to run...

Hectal
Back to the lesson: Topic 4.1 — Responding to Events
React · Example 3 of 3

preventDefault: forms and links

onSubmit goes on the <form>, not on the button, so pressing Enter in the input submits too. Remove a preventDefault() line and run again: the preview reports the submit or the link instead.

You make a component react to the user by passing a function to an event prop such as onClick; React calls that function with an event object when the event happens, and the event bubbles up through parent handlers unless you stop it.

Change the code and press Run (Ctrl+Enter). Predict what will happen first, then break it on purpose and read what changes. Your edits are saved and match the lesson page.

Ready for more? This phase has 5 hands-on exercises with automatic checks.

Practice questions

Write the code in the editor, run it, then open the model answer to compare.

01

Make a ColorSwitch component that takes an onChangeColor prop. Its button must change the page colour (through the parent) but must not trigger the parent div's own onClick that counts clicks.

02

Write a form with one input name that logs Hello, <name>! on submit without reloading the page.

Explain it without notes

01

What is the difference between onClick={handleClick} and onClick={handleClick()}?

02

What are the naming conventions for handlers and handler props, and why do they help?

03

Explain event propagation in React and how stopPropagation and preventDefault differ.

04

What is e.target versus e.currentTarget?

preventDefault: forms and links

Preview

Press Run to see the page.

Console

Nothing logged yet.

Expected console output

Signing up asha@example.com | default prevented: true
Link click handled in JavaScript