Requirements: We have hierarchy of components in parent-child relationship. A, B, C, D are components .A is parent of B, B is parent of C, C is parent of D. We have to send data from A to D
Step1: Create All components A.js, B.js, C.js, D.js in proper hierarchy.
Step2: Create Context.js file & write the following code.
import React from 'react';
var myContext = React.createContext(); // To create the context
export default myContext;
Step3: Write Following code in A.js
import React, { Component } from "react";
import B from "./B";
import myContext from "./ContextAPI";
class A extends Component {
constructor(props) {
super(props);
this.state = {
name: "Pankaj",
city: "Mumbai",
};
}
render() {
return (
<div className="container mt-5">
<div className="row">
<div className="col">
<div className="card">
<div className="card-header bg-dark text-white">
<h2>A Component</h2>
</div>
<div className="card-body">
<myContext.Provider value={this.state}>
<B />
</myContext.Provider>
</div>
</div>
</div>
</div>
</div>
);
}
}
export default A;
Step4: Write following code in B.js
import React, { Component } from "react";
import C from "./C";
class B extends Component {
render() {
return (
<div className="container">
<div className="row">
<div className="col">
<div className="card">
<div className="card-header bg-primary text-white">
<h2>B Component</h2>
</div>
<div className="card-body">
<C />
</div>
</div>
</div>
</div>
</div>
);
}
}
export default B;
Step5: Write following code in C.js
import React, { Component } from "react";
import D from "./D";
class C extends Component {
render() {
return (
<div className="container">
<div className="row">
<div className="col">
<div className="card">
<div className="card-header bg-secondary text-white">
<h2>C Component</h2>
</div>
<div className="card-body">
<D />
</div>
</div>
</div>
</div>
</div>
);
}
}
export default C;
Step6: Write following code in D.js
import React, { Component } from "react";
import myContext from "./ContextAPI";
class D extends Component {
render() {
return (
<div className="container">
<div className="row">
<div className="col">
<div className="card">
<div className="card-header bg-info text-white">
<h2>D Component</h2>
</div>
<div className="card-body">
<myContext.Consumer>
{(data) => {
return (
<div>
<p>{data.name}</p>
<p>{data.city}</p>
</div>
);
}}
</myContext.Consumer>
</div>
</div>
</div>
</div>
</div>
);
}
}
export default D;
No comments:
Post a Comment