How to Set Active Class to Map Elements in React Js

We will learn how to add an active class to mapped list elements in React js. To build this tiny feature, we will need certain ingredients such as a basic react app, a simple function component, useState and useEffect hooks.

React is the most popular front-end framework having the highest download in the node package manager realm. It is coupled with powerful features that distinguish it from other frameworks.

Web developers love to sharpen their skills in React due to its popularity. Today, in this post, we will go deep down and cover specific nuances of active class concepts in React.

To give you the demo of adding an active class to the list item. We will use a REST API that invokes the api response through fetch api.

We will get the data, bind it with the useEffect hook and display the results as list items with the bootstrap list component and use the useState hook to set the active class on mapped items.

React Add Active Class to Map Item using On Click Event Handler Tutorial

  • Step 1: Download React App
  • Step 2: Install Bootstrap Library
  • Step 3: Build New Component
  • Step 4: Set Add Active Class
  • Step 5: Update Global Component
  • Step 6: Invoke React Application

Download React App

To illustrate the demo of active class in React, we need to install a fresh react application. You can jump onto the subsequent step if app is already created.

npx create-react-app react-vlog

Your app is downloaded, now you need to move inside the project folder.

cd react-vlog

Install Bootstrap Library

The bootstrap module is not a compulsion; however, we are installing it so that we won’t have to waste our time writing CSS from scratch.

npm install bootstrap

Build New Component

Create components/ directory, next create User.js file and add the provided code.

import React from 'react'

function User() {
  return (
    <div>User</div>
  )
}

export default User

Set Add Active Class

Previously, we created the components/User.js file, so the next thing we will do is to add the code into the file.

import React, { useState, useEffect } from 'react'

function User() {
  const [user, setUser] = useState([])
  const [active, setActive] = useState(null)

  const getRes = () => {
    fetch('https://jsonplaceholder.typicode.com/users')
      .then((res) => res.json())
      .then((json) => setUser(json))
      .catch((error) => console.log(error))
  }

  useEffect(() => {
    getRes()
  }, [])

  return (
    <div>
      <h2 className="mb-2">
        React Add Active Class to Mapped List Item Example
      </h2>
      <ul className="list-group">
        {user.map((res) => {
          return (
            <li
              key={res.id}
              onClick={() => setActive(res)}
              className={`list-group-item ${active == res && 'active'}`}
            >
              {res.name}
            </li>
          )
        })}
      </ul>
    </div>
  )
}

export default User

Update Global Component

We created a separate component for conjugating the list items, we forgot to register it to the main component. Therefore, we will add or import the User component in App.js file.

import React from 'react'
import 'bootstrap/dist/css/bootstrap.min.css'
import User from './components/User'

function App() {
  return (
    <div>
      <User />
    </div>
  )
}

export default App

Invoke React Application

The last thing we will do is to start the react application through the provided command:

npm start

Now, you can view the application using the suggested url:

http://localhost:3000

How to Set Active Class to Map Elements in React Js

Conclusion

In general, an active class is applied to the menu items the user is currently seeing. It ideally makes the user know which part of the navigation element is active.

The primary purpose of the active class is to help the user to know the element state.