Intro to React > List Element Callbacks
List Element Callbacks
In the previous lesson, we used the SyntheticEvent's target to find the name attribute on each element. Most of the time, you would prefer to instead create individual, dynamic callbacks for each element in the list, rather than use the same callback and reference the target's name.
This is accomplished by mapping over the list elements as we would normally do, but for the callback, we declare an inline anonymous function. Inside the function body, we reference the name
passed in from the map
callback that's run for each element.
Why does this work? Well, JavaScript has created a closure for the element's callback function, so each specific name
is always in scope when the onClick
handler is fired when clicking on a button. Neat!
const crew = [{ name: "Joe" }, { name: "Mark" }, { name: "Bob" }]; function User({ name, onClick }) { return <button onClick={onClick}> {name} </button>; } export default function App() { // callback is called with our own arguments function sayHello(name) { alert("hello, " + name); } return ( <div> <h1> 🏴☠️ The Captain's Crew </h1> <p> Tiny User Management System (TUMS) </p> {crew.map(({ name }, i) => ( <User key={`task-${i}`} name={name} onClick={() => { sayHello(name); }} /> ))} </div> ); }