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 the updating phase, the component gets updated while being present in the DOM. In the unmounting phase, the component is removed from the DOM.
Prerequisites
Steps to Create React Application:
Step 1: Create a React application using the following command:
npx create-react-app mountdemo
Step 2: After creating your project folder i.e. mountdemo, move to it using the following command:
cd mountdemo
Project Structure:
Example: Lifecycle methods in this example shows the logs for component mount in the console.
Javascript
import React from "react" ; class App extends React.Component { constructor(props) { super (props); this .state = { num: 0 }; this .clickHandler = this .clickHandler.bind( this ); } // Button onClick callback function clickHandler(event) { this .setState((state) => ({ num: state.num + 1 })); } // Component lifecycle methods // Triggered when component is mounted componentDidMount() { console.log( "Mounted" ); } // Triggered when component is updated componentDidUpdate() { console.log( "Updated" ); } render() { console.log( "Rendered" ); return ( <div> <h1>Demo App</h1> <p>Number: { this .state.num}</p> <button onClick={ this .clickHandler}> increment </button> </div> ); } } export default App; |
Step to Run Application: Run the application using the following command from the root directory of the project:
npm start
Output: This output will be visible on the http://localhost:3000/ on the browser window.
Contact Us