JSX Event listeners
Events in React work in a similar way they do in HTML, except the event attribute on the element is camelCased, ie: onClick
instead of onclick
, and a function is passed into the React prop instead of a string.
React will fire a SyntheticEvent instead of a regular native browser event that you might be familiar with if you've done vanilla JavaScript development. The event contains the same information as the native browser event.
In the example to the right, we attach event handlers to buttons rendered inside User components. We pass the name
attribute through as a User prop to be used as an html attribute on the button
. This allows us to access e.target.name
and know which pirate is speaking to us.
In the next lesson, we'll discuss an easier pattern to accomplish this by wrapping the sayHello
callback in another function which traps the current pirate's name inside a closure to be accessed through the callback.
const crew = [{ name: "Joe" }, { name: "Mark" }, { name: "Bob" }]; // destructuring the props to pull name function User({ name, onClick }) { return ( <button onClick={onClick} name={name}> {" "} {name}{" "} </button> ); } export default function App() { function sayHello(e) { alert("hello, " + e.target.name); } return ( <div> <h1> 🏴☠️ The Captain's Crew </h1> <p> Tiny User Management System (TUMS) </p> {/* destructuring the crew object to name */} <h3> Please select a user </h3> {crew.map(({ name }, i) => ( <User key={`task-${i}`} name={name} onClick={sayHello} /> ))} </div> ); }