ComponentwillReceiveprops method in React js
React will call a method when the component is about to receive new props . This is the first method that will be called when a component is going to receive a new set of props. Defining this method is a good time to look for updates to specific props as it gives us an opportunity to calculate changes and update our component's internal state. This is the time when we can update our state based on new props.
contianer.js file is displayed below
1import React from "react";
2export default class Container extends React.Component {
3 constructor(props) {
4 super(props);
5 this.state = {
6 value: this.props.value
7 };
8 }
9 componentWillReceiveProps(nextProps) {
10 console.log("next property ", nextProps.value);
11 console.log("current value", this.state.value);
12 this.setState((prevState) => {
13 const value = prevState.value + nextProps.num;
14 return {
15 value
16 };
17 });
18 }
19 render() {
20 console.log("lolo", this.props.value);
21 return (
22 <>
23 <h4>{this.props.value}</h4>
24 </>
25 );
26 }
27}
index.js file is displayed below
1import "./styles.css";
2import React from "react";
3import Container from "./contianer";
4
5export default class App extends React.Component {
6 constructor(props) {
7 super(props);
8 this.state = {
9 value: 0,
10 status: false
11 };
12 }
13 handleVlaue = () => {
14 console.log("kokokoko");
15 this.setState({
16 status: true,
17 value: this.state.value + 1
18 });
19 console.log("check", this.state.status);
20 };
21 render() {
22 console.log("kok", this.state.status);
23 return (
24 <>
25 <button onClick={() => this.handleVlaue()}>Click to Add</button>
26
27 {this.state.status === true ? (
28 <Container value={this.state.value} />
29 ) : null}
30 </>
31 );
32 }
33}
Here is the link of live example which we done so far:
Click here
About
Moiz is a software engineer from Arid University with a passion for writing tech tutorials and doing coding. I am continously produce JavaScript and other web development technology tutorials in concepts through easy-to-understand explanations written in plain English.I have expertise in next js ,react js ,javascript,html,bootstrap and node js.
Follow him on TwitterHassan is a software engineer from kohat university of science and technology with a passion for writing tech tutorials and doing javascript practices on daily basis.I have expertise in next js ,react js ,javascript,html,bootstrap and node js. Problem Solving and making concpets is my strong point.
Follow him on TwitterTags
Click to see all tutorials tagged with: