0
0
Reactframework~30 mins

Passing arguments to handlers in React - Mini Project: Build & Apply

Choose your learning style9 modes available
Passing arguments to handlers in React
📖 Scenario: You are building a simple React app that shows a list of fruits. When you click a fruit's button, it should show an alert with the fruit's name.
🎯 Goal: Create a React functional component that renders buttons for each fruit. When a button is clicked, it calls a handler function with the fruit name as an argument.
📋 What You'll Learn
Create a list of fruits as an array
Create a handler function that accepts a fruit name argument
Render buttons for each fruit using map
Pass the fruit name argument to the handler when a button is clicked
💡 Why This Matters
🌍 Real World
Passing arguments to event handlers is common in React apps to identify which item was interacted with, like selecting a product or toggling a setting.
💼 Career
Understanding how to pass arguments to handlers is essential for React developers to build interactive and dynamic user interfaces.
Progress0 / 4 steps
1
Create the fruits array
Create a constant array called fruits with these exact string values: 'Apple', 'Banana', 'Cherry'.
React
Need a hint?

Use const fruits = ['Apple', 'Banana', 'Cherry']; to create the array.

2
Create the handler function
Create a function called handleClick that takes one parameter called fruit. Inside the function, call alert with the message `You clicked ${fruit}` using a template string.
React
Need a hint?

Define function handleClick(fruit) { alert(`You clicked ${fruit}`); }.

3
Render buttons for each fruit
Create a React functional component called FruitButtons. Inside it, return a <div> that contains a fruits.map call. Use fruit as the iterator variable. For each fruit, render a <button> with the text {fruit}.
React
Need a hint?

Use fruits.map(fruit => <button key={fruit}>{fruit}</button>) inside the return.

4
Pass fruit argument to click handler
In the FruitButtons component, add an onClick attribute to each <button>. Set it to an arrow function that calls handleClick with the current fruit as argument.
React
Need a hint?

Use onClick={() => handleClick(fruit)} on the button.