How to Set Dynamic Class to HTML Body in React Js

How to add HTML classes to body element dynamically when moving from one route to another route in React js app. You will need a single React hook named useEffect hook to include dynamic classes component-wise or HTML elements in React.

The useEffect hook helps you perform side effects in react components. In general useEffect hook is ideally used for rendering data and updating the DOM.

The useEffect hook tells React to do something or take some action after the component renders. We can pass the dependency array as a value in the useEffect hook, so whichever value you pass into the dependency array, the useEffect hook will trigger only when it detects the change in the dependency array’s value.

We also define the return function in the useEffect hook; it is primarily known as the cleanup function; it works asynchronously and runs the cleanup function before performing a new side effect.

React Add Classes to React Body HTML Element Tutorial

  • Step 1: Download React App
  • Step 2: Build New Components
  • Step 3: Setting Up Routes
  • Step 4: Create Nav Elements
  • Step 5: Include Dynamic Classes in React
  • Step 6: Start React Server

Download React App

The first thing is to type and execute the provided command and download a new react app.

npx create-react-app react-blog

Now, app is ready so step inside the project’s folder.

cd react-blog

Build New Components

Inside your project’s src/ folder make components/Home.js file.

import React from 'react'

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

export default Home

Within your app’s src/ directory make components/Blog.js file.

import React from 'react'

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

export default Blog

Inside your project’s src/ folder make components/Single.js file.

import React from 'react'

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

export default Single

Setting Up Routes

Go to the terminal, and on the command prompt, type the suggested command; this command will install the router dom’s latest version as soon as you hit enter.

npm install react-router-dom@6

Next, move to the App.js file that you can found in the src directory, import the components and the router dom api module such as Routes, Route and BrowserRouter.

import '../node_modules/bootstrap/dist/css/bootstrap.min.css'
import { BrowserRouter, Routes, Route } from 'react-router-dom'

import Home from './components/Home'
import Blog from './components/Blog'
import Single from './components/Single'

export default function App() {
  return (
    <div className="container mt-3">
      <BrowserRouter>
        <Routes>
          <Route path="/" element={<Home />} />
          <Route path="/blog" element={<Blog />} />
          <Route path="/single" element={<Single />} />
        </Routes>
      </BrowserRouter>
    </div>
  )
}

Create Nav Elements

We are adding NavLink in the Home.js file for setting up the menu items.

The NavLink is a particular version of the that will add styling attributes to the rendered element when it matches the current URL.

import { NavLink } from 'react-router-dom'

const Home = () => {
  return (
    <div>
      <nav className="nav">
        <NavLink className="nav-link" to="/">
          Home
        </NavLink>

        <NavLink className="nav-link" to="/blog">
          Blog
        </NavLink>

        <NavLink className="nav-link" to="/single">
          Blog Details
        </NavLink>
      </nav>
    </div>
  )
}

export default Home

Include Dynamic Classes in React

The useEffect hook is mainly used to perform side effects; we are setting the dynamic class when the component is ready and removing the class when the component doesn’t exist in dom.

Place the given 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-dynamic-class')
    return () => {
      document.body.classList.remove('home-dynamic-class')
    }
  }, [])

  return (
    <div>
      <nav className="nav">
        <NavLink className="nav-link" to="/">
          Home
        </NavLink>

        <NavLink className="nav-link" to="/blog">
          Blog
        </NavLink>

        <NavLink className="nav-link" to="/single">
          Blog Details
        </NavLink>
      </nav>
    </div>
  )
}

export default Home

Place the suggested code to components/Blog.js file:

import { useEffect } from 'react'

const Blog = () => {
  useEffect(() => {
    document.body.classList.add('blog-dynamic-class')
    return () => {
      document.body.classList.remove('blog-dynamic-class')
    }
  }, [])

  return <div>Blog</div>
}

export default Blog

We have to add the offered code to the components/Single.js file:

import { useEffect } from 'react'

const Single = () => {
  useEffect(() => {
    document.body.classList.add('single-dynamic-class')
    return () => {
      document.body.classList.remove('single-dynamic-class')
    }
  }, [])

  return <div>Single</div>
}

export default Single

Start React Server

The final task is remaining and that is to run the given command and start the react server.

npm start

We are ready to view the app on the browser.

http://localhost:3000

How to Set Dynamic Class to HTML Body in React Js