AI Hints
Home›React Tutorial›Events and State
React · Lesson 19 of 120

Events

OnClick.

⏱ 2 min read▶ Video at 14:25🎓 Free
Watch this lesson in the React courseWatch on YouTube ↗Full React course

Pages come alive when they respond to the user. In React, you pass a function to an event prop, like on click. React calls it when the event happens.

  • Respond to users
  • Pass a function
  • React calls it

Handling a click

Handle click is a normal function. We pass it to the button's on click prop, without calling it. When the button is clicked, the message is logged. We click it twice. Run it.

App.jsxjsx
export default function App() {
  function handleClick() {
    console.log("Added to basket!");
  }

  return (
    <div>
      <h2>Trail 500</h2>
      <button id="add" onClick={handleClick}>Add to basket</button>
    </div>
  );
}
Output
Added to basket!
Added to basket!
Also uses style.css
body{font-family:-apple-system,Helvetica,Arial,sans-serif;margin:22px;font-size:21px;color:#1d1d1f;background:#fafafa}
h1{font-size:34px;margin:0 0 14px} h2{font-size:26px;margin:0 0 10px}
button{font-size:19px;padding:9px 18px;border-radius:9px;border:0;background:#61dafb;color:#111;font-weight:600;margin:4px 6px 4px 0}
input{font-size:19px;padding:8px 10px;border:2px solid #bbb;border-radius:8px}
li{margin:5px 0} .box{padding:14px;border-radius:12px;background:#fff;border:2px solid #ddd;margin:8px 0}
.done{text-decoration:line-through;color:#999} small{color:crimson;display:block;font-size:16px} .big{font-size:64px;font-weight:800}
Also uses actions.json
[{"click": "#add", "times": 2}]

Common mistake

Write on click equals handle click, not handle click with brackets. With brackets, the function runs immediately while rendering, instead of on the click. To pass arguments, wrap it in an arrow function.

keyvalue
RightonClick={handleClick}
WrongonClick={handleClick()}
With argsonClick={() => add(id)}
OthersonChange, onSubmit

Summary

Pass a function to an event prop, and React calls it when the event happens. Next, state.

Key takeaways
  • onClick
  • Pass, don't call
  • Arrow for args
Next up: State — useState