Skip to content
Related Articles

Related Articles

How to change body class before component is mounted in react?
  • Difficulty Level : Medium
  • Last Updated : 20 Jan, 2021

We can change body class before the component is mounted in ReactJS using the following approach:

Prerequisite: React Component LifeCycle

The lifecycle of react components is as follows:

  1. Initialization
  2. Mounting
  3. Updating
  4. Unmounting

Example: Changing the body class before mounting in the Initialization stage. The sequence of Execution:

Javascript



filter_none

edit
close

play_arrow

link
brightness_4
code

import React,{ Component }  from 'react';
   
class App extends Component {
  
  // Gets called 1st place
  constructor(props) {
    super(props);
  }
  
  // Gets called at 2nd place
  render() {
    return (
        <h1>GeeksforGeeks</h1>
    );
  }
  
  // Gets called at 3rd place
  componentDidMount(){
     // Code
  }
}
  
export default App;

chevron_right


Explanation: In the Initialization stage, the first thing that gets called is the Constructor of the component. We will use the Constructor to make our changes. We can get the reference of the body element in the constructor using the following code:

let bodyElement = document.getElementsByTagName('body')[0];

Creating React Application:

Step 1: Create a React application using the following command:

npx create-react-app foldername

Step 2: After creating your project folder i.e. foldername, move to it using the following command:

cd foldername

Project Structure: It will look like the following.

Project Structure

Filename-App.css:

css

filter_none

edit
close

play_arrow

link
brightness_4
code

* {
  margin: 30px;
}
  
h1 {
  color: white;
  text-shadow: 1px 1px black;
}
  
.active {
  background-color: green;
}

chevron_right


Filename-App.js:

Javascript

filter_none

edit
close

play_arrow

link
brightness_4
code

import React, { Component } from 'react';
import "./App.css"
  
class App extends Component {
  
  constructor(props) {
  
    // This will call the constructor of the parent
    super(props);
  
    // Taking reference of body element
    let bodyElement = document.getElementsByTagName('body')[0];
  
    // Changing the class of body Before mounting
    bodyElement.className = "active";
  }
  
  componentDidMount() {
  }
  
  render() {
    return (
      <h1>Geeks For Geeks</h1>
    );
  }
}
  
export default App;

chevron_right


Step to Run Application: Run the application using the following command from the root directory of the project:

npm start

Output: Now open your browser and go to http://localhost:3000/, you will see the following output:

  • Before Component Is Mounted:

  • After Component Is Mounted:

full-stack-img

My Personal Notes arrow_drop_up
Recommended Articles
Page :