Altcademy - a Forbes magazine logo Best Coding Bootcamp 2023

How to target single item in list with onclick when mapping in ReactJS

Understanding the Basics

To grasp the concept of targeting a single item in a list with onClick when mapping in ReactJS, it's essential to understand some fundamental concepts.

In programming, a list is like a shopping list. It's a collection of individual items that you can view all at once, or one at a time. In the world of ReactJS, this is typically called an array. We can "map" over this array, which is like going through each item on our shopping list one by one.

When we talk about an onClick event, imagine it like turning on a light switch. It's something that happens in response to a user's action - in this case, a click.

Let's now dive deeper into how we can use these concepts in ReactJS.

Mapping Over Lists in ReactJS

Mapping is like taking a walk down your shopping list, looking at each item one by one. In JavaScript, we use the map() function to do this. Here's a simple example:

const groceries = ['Apples', 'Oranges', 'Bananas']

const GroceriesList = () => {
  return (
    <ul>
      {groceries.map((item) => {
        return <li>{item}</li>
      })}
    </ul>
  )
}

In this example, we created a list of groceries. We then used .map() to go through each item on the list. For each item, we returned a <li> (list item) element that displays the name of the grocery item.

Adding an onClick Event

Now that we have our list, let's add the light switch - the onClick event. This will allow us to perform a certain action when a user clicks on a grocery item.

const groceries = ['Apples', 'Oranges', 'Bananas']

const GroceriesList = () => {
  const handleClick = (item) => {
    alert(`You clicked on ${item}`)
  }

  return (
    <ul>
      {groceries.map((item) => {
        return <li onClick={() => handleClick(item)}>{item}</li>
      })}
    </ul>
  )
}

In this code, we added a handleClick function that shows an alert whenever a user clicks on a grocery item. We then added the onClick event to each <li> element. Notice the use of arrow function () => handleClick(item). This ensures that the handleClick function is not called immediately when the page loads, but only when the list item is clicked.

Targeting a Single Item

So, we have a list of items and a way to interact with them. But what if we want to perform an action on a single, specific item? For example, let's consider highlighting a selected grocery item.

const groceries = ['Apples', 'Oranges', 'Bananas']

const GroceriesList = () => {
  const [selectedItem, setSelectedItem] = React.useState(null)

  const handleClick = (item) => {
    setSelectedItem(item)
  }

  return (
    <ul>
      {groceries.map((item) => {
        return (
          <li
            style={{ backgroundColor: item === selectedItem ? 'yellow' : 'transparent' }}
            onClick={() => handleClick(item)}
          >
            {item}
          </li>
        )
      })}
    </ul>
  )
}

In this example, we introduced a new concept called state. Think of state as a memory box that holds the value of a certain variable (in this case, the selected item). The useState function is like a magic spell that allows us to create and manipulate this memory box.

When a user clicks on a list item, we store the name of the item in the selectedItem state using the setSelectedItem function. We then check if the current item is the selected item by comparing item === selectedItem. If it is, we change the background color to yellow.

Conclusion

Imagine you're a magician. The array is your hat, and the map() function is your magic wand that you wave at the hat to see its contents. The onClick function is another spell that you cast, which allows you to interact with the items in the hat. The useState function is your magic box where you can keep anything you want, in this case, the selected item from the hat.

A magician needs to practice to perfect his tricks. The same goes for you as a developer. The more you practice these concepts, the more comfortable you'll be in using them to build interactive and dynamic web applications with ReactJS. Remember, the key is understanding the concepts, and then applying them through practice. Keep coding, keep learning, and keep performing magic with ReactJS!