How to change body class before component is mounted in react?
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:
Example: Changing the body class before mounting in the Initialization stage. The sequence of Execution:
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');
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:
Project Structure: It will look like the following.
Step to Run Application: Run the application using the following command from the root directory of the project:
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: