23 January 2020

componentDidMount and componentDidUpdate in react Class Component

  • Create Components folder under src folder
  • Add ClassDidMountDidUpdateEXP1.js file and add below Code
import React, { Component } from "react";

class ClassDidMountDidUpdateEXP1 extends Component {
constructor(props) {
super(props);
this.state = {
role: "React developer",
name: "Adi"
};
}

componentDidMount() {
console.log(
`didMount: Hello I'm ${this.state.name} and I'm a ${this.state.role}`
);
}

componentDidUpdate() {
console.log(
`didUpdate: Hello I'm ${this.state.name} and I'm a ${this.state.role}`
);
}

render() {
return (
<div>
<center>
<h4> componentDidMount & componentDidUpdate in Class Component</h4>
</center>
<p>{`Hello I'm ${this.state.name} and I'm a ${this.state.role}`}</p>
<button
onClick={() => this.setState({ name: "JC", role: ".net developer" })}
>
Change me
</button>
</div>
);
}
}

export default ClassDidMountDidUpdateEXP1;
  • Open index.js file and update code as below
import React from "react";
import ReactDOM from "react-dom";
import ClassDidMountDidUpdateEXP1 from "./components/ClassDidMountDidUpdateEXP1";

function App() {
return (
<div className="App">
<ClassDidMountDidUpdateEXP1 />
</div>
);
}

const rootElement = document.getElementById("root");
ReactDOM.render(<App />, rootElement);

Output:



No comments:

Post a Comment