React componentDidMount() Method
The componentDidMount() method format is as follows:
componentDidMount()
The componentDidMount() method is invoked immediately after a component is mounted (inserted into the DOM tree).
Initializations that require DOM nodes should be placed in the componentDidMount() method.
The following example will first output tutorialpro and then use the componentDidMount()
method to output google after the component is mounted:
Example
class Header extends React.Component {
constructor(props) {
super(props);
this.state = {favoritesite: "tutorialpro"};
}
componentDidMount() {
setTimeout(() => {
this.setState({favoritesite: "google"})
}, 1000)
}
render() {
return (
<h1>My favorite website is {this.state.favoritesite}</h1>
);
}
}
ReactDOM.render(<Header />, document.getElementById('root'));