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:
- Initialization
- Mounting
- Updating
- Unmounting
Example: Changing the body class before mounting in the Initialization stage. The sequence of Execution:
Javascript
import React,{ Component } from 'react' ;
class App extends Component {
constructor(props) {
super (props);
}
render() {
return (
<h1>GeeksforGeeks</h1>
);
}
componentDidMount(){
}
}
export default App;
|
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
* {
margin : 30px ;
}
h 1 {
color : white ;
text-shadow : 1px 1px black ;
}
.active {
background-color : green ;
}
|
Filename-App.js:
Javascript
import React, { Component } from 'react' ;
import "./App.css"
class App extends Component {
constructor(props) {
super (props);
let bodyElement = document.getElementsByTagName( 'body' )[0];
bodyElement.className = "active" ;
}
componentDidMount() {
}
render() {
return (
<h1>Geeks For Geeks</h1>
);
}
}
export default App;
|
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:
Last Updated :
20 Jan, 2021
Like Article
Save Article
Share your thoughts in the comments
Please Login to comment...