The render() method is called when a component is updated, as it needs to re-render the HTML to the DOM with the changes. In the example below, a button is used to change the favorite color to blue.
Example:
Press the button to update the component’s state.
class Header extends React.Component {
constructor(props) {
super(props );
this.state = {favoritecolor: "red"};
}
changeColor = () => {
this.setState({favoritecolor: "blue"});
}
render() {
return (
<div> <h1>My Favorite Color is {this.state .favoritecolor }</h1> <button type="button" onClick={this.changeColor}>Change color</button> </div>
);
} }
const root = ReactDOM .createRoot(document .getElementById('root'));
root .render(<Header />);
|
getSnapshotBeforeUpdate
Though the example may seem complex, here’s the process:
When the component mounts, it initially renders with “red.” After one second, the color changes to “yellow,” triggering the update phase. The getSnapshotBeforeUpdate() method runs, writing a message to DIV1, followed by componentDidUpdate(), which writes to DIV2.
Example:
Use the getSnapshotBeforeUpdate() method to determine the previous state of the object before the update occurred.
class Header extends React.Component {
constructor(props) {
super(props );
this.state = {favoritecolor: "red"};
}
componentDidMount() {
setTimeout(() => {
this.setState({favoritecolor: "yellow"})
}, 1000)
}
getSnapshotBeforeUpdate(prevProps, prevState) {
document .getElementById("div1").innerHTML =
"Before the update, the favorite was " + prevState .favoritecolor ;
}
componentDidUpdate() {
document .getElementById("div2").innerHTML =
"The updated favorite is " + this.state .favoritecolor ;
}
render() {
return (
<div> <h1>My Favorite Color is {this.state .favoritecolor }</h1> <div id="div1"></div> <div id="div2"></div> </div>
);
} }
const root = ReactDOM .createRoot(document .getElementById('root'));
root .render(<Header />);
|