How to Add Active Class in Map Items in React Js

Last updated on: by Digamber

In this quick tutorial, we will show you how to quite easily add the active class or current class on the mapped list item in React js application.

To add the current class by clicking on the current list item we will use the useState hook in React function component.

In UI, An Active Class is a Class that owns its own invocation, ideally when invoked. It is generally used when you want to make your HTML element stand apart in a group of elements.

In this React active class on list element example, we will learn to create this tiny feature in React js environment.

We will help you learn how to apply the active class on a list item. It will help the user to understand what item he is currently viewing.

How to Add Active Class to Clicked Item in React Js Mapped Items

  • Step 1: Install React Project
  • Step 2: Add Bootstrap Module
  • Step 3: Create Component File
  • Step 4: On Clicked Add Active Class to Mapped Item
  • Step 5: Update App Js Component
  • Step 6: View App in Browser

Install React Project

We will start with installing the create-react-app tool in our development system:

npm install create-react-app --global

You may now create a brand new React project:

npx create-react-app react-demo

Use the command to enter into the project folder.

cd react-demo

Add Bootstrap Module

In this step, we will add the bootstrap module; for this demo code we will not be writing CSS from scratch. Instead, we will take the help of Bootstrap UI CSS and create its List group component.

npm install bootstrap

Create Component File

Head over to src/ folder in here you need to create components/ folder and List.js file.

import React from 'react'
function List() {
  return (
    <div>List</div>
  )
}
export default List

On Clicked Add Active Class to Mapped Item

In this step, you have to paste the entire given code into the components/List.js file.

import React, { useState, useEffect } from 'react'
function List() {
  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 className="mb-3">React Js Active Class on List Item Example</h2>
      <ul className="list-group">
        {list.map((item) => {
          return (
            <li
              key={item.id}
              onClick={() => setActive(item)}
              className={`list-group-item ${active == item && 'active'}`}
            >
              {item.name}
            </li>
          )
        })}
      </ul>
    </div>
  )
}
export default List

We are fetching the data from the real api to create the active class feature on the mapped item.

Set the state to null on initial load, update the setActive state using the onClick handler and add the current class on the list item in React component.

Update App Js Component

Open src/App.js file, import the List component at the top of the file and also define the component inside the App() function.

import React from 'react'
import 'bootstrap/dist/css/bootstrap.min.css'
import List from './components/List'
function App() {
  return (
    <div className="container mt-5">
      <List />
    </div>
  )
}
export default App

View App in Browser

To view the app in the browser, we will need to run the react server:

npm start

On the following link we will test the app:

http://localhost:3000

How to Add Active Class in Map Items in React Js

Digamber

I am Digamber, a full-stack developer and fitness aficionado. I created this site to bestow my coding experience with newbie programmers. I love to write on JavaScript, ECMAScript, React, Angular, Vue, Laravel.