Skip to content
geeksforgeeks
  • Courses
    • DSA to Development
    • Get IBM Certification
    • Newly Launched!
      • Master Django Framework
      • Become AWS Certified
    • For Working Professionals
      • Interview 101: DSA & System Design
      • Data Science Training Program
      • JAVA Backend Development (Live)
      • DevOps Engineering (LIVE)
      • Data Structures & Algorithms in Python
    • For Students
      • Placement Preparation Course
      • Data Science (Live)
      • Data Structure & Algorithm-Self Paced (C++/JAVA)
      • Master Competitive Programming (Live)
      • Full Stack Development with React & Node JS (Live)
    • Full Stack Development
    • Data Science Program
    • All Courses
  • Tutorials
    • Data Structures & Algorithms
    • ML & Data Science
    • Interview Corner
    • Programming Languages
    • Web Development
    • CS Subjects
    • DevOps And Linux
    • School Learning
  • Practice
    • Build your AI Agent
    • GfG 160
    • Problem of the Day
    • Practice Coding Problems
    • GfG SDE Sheet
  • Contests
    • Accenture Hackathon (Ending Soon!)
    • GfG Weekly [Rated Contest]
    • Job-A-Thon Hiring Challenge
    • All Contests and Events
  • JS Tutorial
  • JS Exercise
  • JS Interview Questions
  • JS Array
  • JS String
  • JS Object
  • JS Operator
  • JS Date
  • JS Error
  • JS Projects
  • JS Set
  • JS Map
  • JS RegExp
  • JS Math
  • JS Number
  • JS Boolean
  • JS Examples
  • JS Free JS Course
  • JS A to Z Guide
  • JS Formatter
Open In App
Next Article:
How to Add a classname/id to React-Bootstrap Component ?
Next article icon

How to change body class before component is mounted in react?

Last Updated : 20 Jan, 2021
Comments
Improve
Suggest changes
Like Article
Like
Report

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
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; 

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; }  h1 {   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) {      // 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; 

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:

Next Article
How to Add a classname/id to React-Bootstrap Component ?

P

pratikraut0000
Improve
Article Tags :
  • Technical Scripter
  • JavaScript
  • Web Technologies
  • Technical Scripter 2020

Similar Reads

  • How to handle empty object before mount in ReactJS ?
    When working with ReactJS, it's common to encounter situations where you need to handle empty objects or uninitialized data before rendering components. when fetching data, it is necessary to load the data and perform various operations on it. However, a challenge arises when the app state lacks the
    3 min read
  • How to change the state of react component on click?
    To change the state of the React component is useful when you are working on a single page application, it simply replaces the content of the existing component for the user without reloading the webpage. We have to set initial state value inside constructor function and set click event handler of t
    2 min read
  • How to Add a classname/id to React-Bootstrap Component ?
    In this article, we will learn how we can add a class name and ID to a React-Bootstrap component. ClassName and ID can be used to target elements while styling and scripting (which means writing logic) the application. Prerequisites:React JSReact-BootstrapSteps to create React app and install bootst
    4 min read
  • How to create Class Component in React?
    JavaScript syntax extension permits HTML-like code within JavaScript files, commonly used in React for defining component structure. It simplifies DOM element manipulation by closely resembling HTML syntax. JSX facilitates the creation of reusable UI building blocks, defined as JavaScript functions
    2 min read
  • What does it mean for a component to be mounted in ReactJS ?
    For a component to be mounted in ReactJS it means to be initialized and inserted in the DOM. Mounting is the initial phase in which the instance of the component is created and inserted into the DOM. When the component gets successfully inserted into the DOM, the component is said to be mounted. In
    2 min read
  • How do you initialize state in a class component?
    In React, class components are a way to create and manage stateful components. Initializing the state is a crucial step when working with class components as it allows you to store and manage dynamic data that can be updated and affect the component's rendering. In this article, we will explore how
    3 min read
  • What are Class Components in React?
    Class components in React are fundamental building blocks for creating reusable, stateful, and interactive user interfaces. Unlike functional components, class components can manage their own state and lifecycle methods, making them a preferred choice for more complex applications before the introdu
    3 min read
  • How to add or remove multiple classes to a ReactJS Component?
    In react we offen need to add or remove multiple classes based on the state and props to update the content dynamically. It can be done with the help of template-literals, className property and by using external npm packages. How to Add or Removed Classes in React?To add or remove multiple classes
    4 min read
  • How to Change Button Text on Click in ReactJS ?
    In this article, we will learn about diverse methods for altering button text dynamically upon clicking on the button. React, a widely embraced JavaScript library for crafting user interfaces provides several approaches to seamlessly achieve this functionality. The key lies in manipulating the compo
    3 min read
  • How to add a CSS class whenever the component is updated in React JS ?
    In this article, we will learn how to add a CSS class conditionally in React JS. If we want to update/add a CSS class when the component is updated or the state/props of components change then we have to conditionally apply the CSS based on the state/props value.  Syntax of adding CSS classes condit
    2 min read
geeksforgeeks-footer-logo
Corporate & Communications Address:
A-143, 7th Floor, Sovereign Corporate Tower, Sector- 136, Noida, Uttar Pradesh (201305)
Registered Address:
K 061, Tower K, Gulshan Vivante Apartment, Sector 137, Noida, Gautam Buddh Nagar, Uttar Pradesh, 201305
GFG App on Play Store GFG App on App Store
Advertise with us
  • Company
  • About Us
  • Legal
  • Privacy Policy
  • In Media
  • Contact Us
  • Advertise with us
  • GFG Corporate Solution
  • Placement Training Program
  • Languages
  • Python
  • Java
  • C++
  • PHP
  • GoLang
  • SQL
  • R Language
  • Android Tutorial
  • Tutorials Archive
  • DSA
  • Data Structures
  • Algorithms
  • DSA for Beginners
  • Basic DSA Problems
  • DSA Roadmap
  • Top 100 DSA Interview Problems
  • DSA Roadmap by Sandeep Jain
  • All Cheat Sheets
  • Data Science & ML
  • Data Science With Python
  • Data Science For Beginner
  • Machine Learning
  • ML Maths
  • Data Visualisation
  • Pandas
  • NumPy
  • NLP
  • Deep Learning
  • Web Technologies
  • HTML
  • CSS
  • JavaScript
  • TypeScript
  • ReactJS
  • NextJS
  • Bootstrap
  • Web Design
  • Python Tutorial
  • Python Programming Examples
  • Python Projects
  • Python Tkinter
  • Python Web Scraping
  • OpenCV Tutorial
  • Python Interview Question
  • Django
  • Computer Science
  • Operating Systems
  • Computer Network
  • Database Management System
  • Software Engineering
  • Digital Logic Design
  • Engineering Maths
  • Software Development
  • Software Testing
  • DevOps
  • Git
  • Linux
  • AWS
  • Docker
  • Kubernetes
  • Azure
  • GCP
  • DevOps Roadmap
  • System Design
  • High Level Design
  • Low Level Design
  • UML Diagrams
  • Interview Guide
  • Design Patterns
  • OOAD
  • System Design Bootcamp
  • Interview Questions
  • Inteview Preparation
  • Competitive Programming
  • Top DS or Algo for CP
  • Company-Wise Recruitment Process
  • Company-Wise Preparation
  • Aptitude Preparation
  • Puzzles
  • School Subjects
  • Mathematics
  • Physics
  • Chemistry
  • Biology
  • Social Science
  • English Grammar
  • Commerce
  • World GK
  • GeeksforGeeks Videos
  • DSA
  • Python
  • Java
  • C++
  • Web Development
  • Data Science
  • CS Subjects
@GeeksforGeeks, Sanchhaya Education Private Limited, All rights reserved
We use cookies to ensure you have the best browsing experience on our website. By using our site, you acknowledge that you have read and understood our Cookie Policy & Privacy Policy
Lightbox
Improvement
Suggest Changes
Help us improve. Share your suggestions to enhance the article. Contribute your expertise and make a difference in the GeeksforGeeks portal.
geeksforgeeks-suggest-icon
Create Improvement
Enhance the article with your expertise. Contribute to the GeeksforGeeks community and help create better learning resources for all.
geeksforgeeks-improvement-icon
Suggest Changes
min 4 words, max Words Limit:1000

Thank You!

Your suggestions are valuable to us.

What kind of Experience do you want to share?

Interview Experiences
Admission Experiences
Career Journeys
Work Experiences
Campus Experiences
Competitive Exam Experiences