Handle clicks on several buttons with one function that takes an argument.
What to build
Three buttons that print which colour was clicked.
Requirements
- Render three
buttonelementsRed,GreenandBlue. - Clicking one prints
Colour: NAMEwithconsole.log, through one shared handler function that takes the colour as an argument.
Constraints
Do not write three separate handler functions.
Example
Clicking Green prints "Colour: Green" in the console.
Why it works
An arrow function on each button passes its own colour to the shared handler, so the logic is written once.
Hints
Hint 1
One function handleClick(colour) and onClick={() => handleClick("Red")} on each button.
Hint 2
You can map over ["Red", "Green", "Blue"] to make the buttons.
Solution
Show one correct solution (try it yourself first)
const COLOURS = ["Red", "Green", "Blue"];
export default function App() {
function handleClick(colour) {
console.log("Colour: " + colour);
}
return (
<div>
{COLOURS.map((colour) => (
<button key={colour} onClick={() => handleClick(colour)}>
{colour}
</button>
))}
</div>
);
}