React – Add Active Class on Selected Item on Dynamic List

In this tutorial, we will discuss how to add an active or any class on a selected item in a dynamic list of items in react application. Users may have a dynamic list of items from which single item need to be selected, to indicate the selected item, an ‘active’ class with CSS style can…

By.

•

min read

In this tutorial, we will discuss how to add an active or any class on a selected item in a dynamic list of items in react application.

Users may have a dynamic list of items from which single item need to be selected, to indicate the selected item, an ‘active’ class with CSS style can be used. This small feature can be achieved by using the useState hook of functional components in React application.

In this guide, we will create a dynamic list using the map function, and then add the active class on the click action. The active items state will be maintained in state variable.

How to add an Active class on Click in Dynamic List in React?

Step 1 – Create React App

Step 2 – Create List Component

Step 3 – Add Active Class on Clicked Item

Step 4 – Update App Component

Step 5 – See In Action

 

 

Step 1 – Create React App

First, make sure your system is having the create-react-app tool installed:

npm install create-react-app --global

next, execute the following comamnd to create a react application with provided name:

npx create-react-app my-react-app

Move inside the react application folder:

cd my-react-app

 

Step 2 – Create List Component

Open the src directory and create the components folder with file named SelectList.js:

Update the src/components/SelectList.js file with the following content:

import React, { useState, useEffect } from "react";
import '..App.css';
function SelectList() {
  const [list, setList] = useState([]);
  const [active, setActive] = useState(null);
  const fetchData = () => {
    fetch("https://jsonplaceholder.typicode.com/users")
      .then((res) => res.json())
      .then((json) => setList(json))
      .catch((e) => console.log(e));
  };
  useEffect(() => {
    fetchData();
  },[]);
  return (
    <div>
      <h2>React Js Selectable Item List Item Example</h2>
      <ul className="list-group">
        {list.map((item) => {
          return (
            <li
              key={item.id}
              onClick={() => setActive(item)}
              className={`list-item ${active == item && "active"}`}
            >
              {item.name}
            </li>
          );
        })}
      </ul>
    </div>
  );
}
export default SelectList;

Using the fetch() function we are fetching the remote list items and creating the list using the map() function.

On each item, we have the onClick handler to set that item in the active state variable. By matching the expression at each item, the active class is getting added to the selected item.

 

Step 3 – Add Active Class on Clicked Item

Add the following CSS snippet and add in the App.css file to highlight the selected item:

.list-item {
  cursor: pointer;
}
.list-item.active {
  background-color: yellow;
}

 

Step 4 – Update App Component

Now, open the App.js file and import the SelectList component as shown below:

import React from "react";
import SelectList from "./components/SelectList";
function App() {
  return (
    <div>
      <SelectList />
    </div>
  );
}
export default App;

 

Step 5 – See In Action

Run your react application in the development web server by hitting the below command:

npm start

It will open the application at the following URL:

http://localhost:3000/

One response to “React – Add Active Class on Selected Item on Dynamic List”

  1. Karan Avatar
    Karan

    •

    Very Helpful Tutorial…Thank You Very Much

Leave a Reply

Your email address will not be published. Required fields are marked *