bugl
bugl
HomeLearnPatternsPathsSearch
HomeLearnPatternsPathsSearch

Loading lesson path

Learn/React/React Core
React•React Core

React Events

Flash cards

Review the key moves

1/4
Core idea

What is the main idea behind React Events?

Lesson checks

Practice each idea before moving on

Short Mimo-style checks built from this lesson's code, terms, and sequence.

1Quick choice

Which statement best captures the main point of this lesson?

2Fill blank

Complete the missing token from the example code.

<___ onClick={shoot}>Take the Shot!</button>
3Order

Put the learning moves in the order that makes the concept easiest to apply.

React has the same events as HTML: click, change, mouseover etc.
Just like HTML DOM events, React can perform actions based on user events.
React Event Object

Just like HTML DOM events, React can perform actions based on user events.

React has the same events as HTML: click, change, mouseover etc.

Adding Events

React events are written in camelCase syntax:

onClick instead of onclick .

React event handlers are written inside curly braces:

onClick={shoot} instead of onclick="shoot()" .

React

<button onClick={shoot}>Take the Shot!</button>

HTML

<button onclick="shoot()">Take the Shot!</button>

Example

Put the shoot function inside the Football component:

function Football() {
 const shoot = () => {
 alert("Great Shot!");
 }
 return ( <button onClick={shoot}>Take the shot!</button> );
}
createRoot(document.getElementById('root')).render( <Football /> );

Passing Arguments

To pass an argument to an event handler, use an arrow function.

Example

Send "Goal!" as a parameter to the shoot function, using arrow function:

function Football() {
 const shoot = (a) => {
 alert(a);
 }
 return ( <button onClick={() => shoot("Goal!")}>Take the shot!</button> );
}
createRoot(document.getElementById('root')).render( <Football /> );

React Event Object

Event handlers have access to the React event that triggered the function.

In our example the event is the "click" event.

Example

Arrow Function: Sending the event object manually:

function Football() {
 const shoot = (a, b) => {
 alert(b.type);
 /* 'b' represents the React event that triggered the function, in this case the 'click' event
 */
 }
 return ( <button onClick={(event) => shoot("Goal!", event)}>Take the shot!</button> );
}
createRoot(document.getElementById('root')).render( <Football /> );

This will come in handy when we look at Form in a later chapter.

Previous

React Props Children

Next

React Conditional Rendering