React Add Dynamic Class Name to Body When Navigating Tutorial

Last updated on: by Digamber

In a web application, we sometimes need to include or add dynamic classes to the HTML elements for specific pages.

In this quick tutorial, we will reveal how to add dynamic classes to body element when navigating from one component to another component in React js application.

For adding the dynamic class in React, we will use the useEffect hook, and we will also create three components and install the latest version of React Router DOM.

When a user goes to any component using the React routers, we will specifically add the class to the body element for that particular component.

The useEffect hook tells React to do something or take some action after the component renders.

It takes an array (dependency array) as a value; whichever value you pass into the useEffect array method, the useEffect hook only invokes when it detects the changes in the dependency array’s value.

The return cleanup function works asynchronously and runs the cleanup function before performing a new side effect.

How to Include Dynamic Class Name to HTML Body in React Js When Navigating the Web Pages

  • Step 1: Build New React Project
  • Step 2: Create Component Files
  • Step 3: Define Routes in React
  • Step 4: Set Up Menu Items
  • Step 5: Add Dynamic Class to Body
  • Step 6: Run React App

Build New React Project

In order to work with React on your local system you have to install the create-react-app tool.

Run the given command to install the module:

npm install create-react-app --global

Then, you can install the React app using the given command:

npx create-react-app react-dynamic-class

Next, move inside the react project:

cd react-dynamic-class

Create Component Files

Make the components/ folder in the src/ directory, after that you have to create given files:

Create Home.js in components/ folder:

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

Make Product.js in components/ folder:

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

Build ProductDetails.js in components/ folder:

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

Define Routes in React

Open the terminal, type the command on the command-prompt then hit enter to install the react-router-dom version 6.

npm install react-router-dom@6 --legacy-peer-deps

Look for the App.js file inside the src/ folder, then import the BrowserRouter, Routes, and Route from the ‘react-router-dom’ package.

Now, define the Routes and Route properties to set up the routing in React.

import '../node_modules/bootstrap/dist/css/bootstrap.min.css'
import Home from './components/Home'
import Product from './components/Product'
import ProductDetails from './components/ProductDetails'
import { BrowserRouter, Routes, Route } from 'react-router-dom'
export default function App() {
  return (
    <div className="container mt-5 text-center">
      <BrowserRouter>
        <Routes>
          <Route path="/" element={<Home />} />
          <Route path="/product" element={<Product />} />
          <Route path="/product-details" element={<ProductDetails />} />
        </Routes>
      </BrowserRouter>
    </div>
  )
}

Set Up Menu Items

Head over to the Home.js file, and import the NavLink module from the ‘react-router-dom’ package.

Then, define the nav items using the NavLink module. Make sure to pass the routing names using the to=”” directive.

import { useEffect } from 'react'
import { NavLink } from 'react-router-dom'
const Home = () => {
  useEffect(() => {}, [])
  return (
    <div className="page-wrapper">
      <nav className="nav">
        <NavLink className="nav-link" to="/">
          Home
        </NavLink>
        <NavLink className="nav-link" to="/product">
          Product
        </NavLink>
        <NavLink className="nav-link" to="/product-details">
          Product Details
        </NavLink>
      </nav>
    </div>
  )
}
export default Home

Add Dynamic Class to Body

Now, we will show you how to include a dynamic class name to the body HTML element.

For adding the dynamic class in HTML within React component while navigating to other components or pages, we will use the useEffect React hook.

The useEffect hook is the most prominent hook in React; it tracks the rendering of the component and performs certain tasks every time a component re-renders.

Add the following code in the components/Home.js file:

import { useEffect } from 'react'
import { NavLink } from 'react-router-dom'
const Home = () => {
  useEffect(() => {
    document.body.classList.add('home-layout')
    return () => {
      document.body.classList.remove('home-layout')
    }
  }, [])
  return (
    <div className="page-wrapper">
      <nav className="nav">
        <NavLink className="nav-link" to="/">
          Home
        </NavLink>
        <NavLink className="nav-link" to="/product">
          Product
        </NavLink>
        <NavLink className="nav-link" to="/product-details">
          Product Details
        </NavLink>
      </nav>
    </div>
  )
}
export default Home

Put the suggested code in the components/Product.js file:

import { useEffect } from 'react'
const Product = () => {
  useEffect(() => {
    document.body.classList.add('product-layout')
    return () => {
      document.body.classList.remove('product-layout')
    }
  }, [])
  return <div className="page-wrapper">Product</div>
}
export default Product

Incorporate the given code in the components/ProductDetails.js file:

import { useEffect } from 'react'
const ProductDetails = () => {
  useEffect(() => {
    document.body.classList.add('product-details-layout')
    return () => {
      document.body.classList.remove('product-details-layout')
    }
  }, [])
  return <div className="page-wrapper">Product Details</div>
}
export default ProductDetails

Run React App

One more type the given command on the console and hit enter to start the app server:

npm start

If you are testing the feature locally use the given url to open the app:

http://localhost:3000

React Add Dynamic Class Name to Body When Navigating Tutorial

Conclusion

We have shown you how to incorporate the dynamic classes in body elements, especially when traversing between various components in React js.

We learned how to use the useEffect hook to add the dynamic classes in React.

positronX.io - Tamso Ma Jyotirgamaya
Digamber

A Full-stack developer with a passion to solve real world problems through functional programming.