CodeBlanks Logo Icon CodeBlanks

Events

Learn to pass a function to event attributes like onClick.

Events

In React, user interaction is caught by event handlers. You listen to a button click with the onClick prop: <button onClick={handleClick}>GO</button>.

The handler is a function starting with a lowercase letter. In braces you pass the function itself, not the call. So onClick={handleClick} is right, onClick={handleClick()} is wrong.

When the click happens, React calls the handler; you do whatever you want there.

Writing a handler

You define the handler inside the component: function handleClick() { ... }. With no parameter, it takes empty parens.

Each render recreates the handler; that is normal. Later we will see useCallback to optimize this.

Inside the handler you can do anything: compute data, call other functions, later update state.

Practice Clickable button

Complete the skeleton. Write a ClickButton component; define a function handleClick inside (body can be empty). Return <button onClick={handleClick}>GO</button>. Export it.

Starter code

App.jsx
// Define ClickButton here

Sample solution

App.jsx
function ClickButton() {
  function handleClick() {}
  return <button onClick={handleClick}>GO</button>;
}

export default ClickButton;

Questions and answers

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

1 Which is correct?

App.jsx
If you add parens, the function runs at once.
  • onClick="handleClick"
  • onClick={handleClick()}
  • onClick={handleClick} Correct answer
  • onClick=handleClick

Explanation: You pass the function itself, not the call.

2 Events: fill in the missing part

Question
<button onClick={____}>GO</button>
Answer
<button onClick={handleClick}>GO</button>

Explanation: You passed the function itself.

3 Events: match the terms

Term Meaning
onClick Click
onChange Change
onSubmit Form submit
onMouseOver Hover

All lessons in Beginner