React componentDidMount()
method
The componentDidMount()
format of the method is as follows:
componentDidMount()
componentDidMount()
method is called immediately after the component is mounted (inserted into the DOM tree).
Initialization that depends on the DOM node should be placed in the componentDidMount()
in the method.
The following example outputs first runoob
and then use the componentDidMount()
method is set to output after the component is mounted google
:
Example
classHeaderextendsReact.Component{constructor(props){super(props);this.state={favoritesite:"runoob"};}componentDidMount(){setTimeout(()=>{this.setState({favoritesite:"google"})},1000)}render(){return(<h1>My favorite website is{this.state.favoritesite}</h1>);}}ReactDOM.render(<Header/>,document.getElementById('root'));