CodeBlanks Logo Icon CodeBlanks

Summary - Events

Write a simple panel where a click on a button increases a counter.

Summary - Events

In this group you learned React events. onClick catches clicks, onChange catches changes, onSubmit catches form submit. You pass a handler function to each.

The handler receives the event object (e). The most used fields are e.target.value (current text) and e.preventDefault() (stop default behavior).

You pass the function itself, not the call. On submit you call preventDefault first.

Practice Events summary task

Complete the skeleton. Write an EventDemo component; define handleClick (no parameter, empty body) and handleSubmit (parameter e, first line e.preventDefault()). Return a <form onSubmit={handleSubmit}> with <button type="submit" onClick={handleClick}>Send</button> inside. Export it.

Starter code

App.jsx
// Define EventDemo here

Sample solution

App.jsx
function EventDemo() {
  function handleClick() {}
  function handleSubmit(e) { e.preventDefault(); }
  return <form onSubmit={handleSubmit}><button type="submit" onClick={handleClick}>Send</button></form>;
}

export default EventDemo;

Questions and answers

Review the lesson questions together with their answers. To test yourself, solve the lesson interactively.

1 Which is wrong?

App.jsx
You pass the function itself to the handler.
  • onClick={handleClick}
  • onClick={handleClick()} is correct Correct answer
  • onSubmit catches form submit
  • e.target.value gives current text

Explanation: onClick={handleClick()} is wrong; parens run it at once.

2 Summary - Events: match the terms

Term Meaning
onClick Click
onChange Change
e.target.value Current text
e.preventDefault() Stop reload

All lessons in Beginner