What is componentDidMount in reactJS?
The componentDidMount() method is called after the component is rendered. This is where you run statements that requires that the component is already placed in the DOM.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 | import React from 'react'; import ReactDOM from 'react-dom'; class Header extends React.Component { constructor(props) { super(props); this.state = {favoritecolor: "red"}; } componentDidMount() { setTimeout(() => { this.setState({favoritecolor: "yellow"}) }, 1000) } render() { return ( <h1>My Favorite Color is {this.state.favoritecolor}</h1> ); } } ReactDOM.render(<Header />, document.getElementById('root')); |
1 2 3 4 5 6 7 8 9 10 11 12 13 14 | <!DOCTYPE html> <html lang="en"> <head> <meta charset="utf-8" /> <meta name="viewport" content="width=device-width, initial-scale=1" /> <title>React App</title> </head> <body> <div id="root"></div> </body> </html> |
If you like this question & answer and want to contribute, then write your question & answer and email to freewebmentor[@]gmail.com. Your question and answer will appear on FreeWebMentor.com and help other developers.