React is a JavaScript library maintained mainly by Facebook. Despite its popularity, it can be a bit tricky to handle data in React. This guide summarizes three approaches to handling data in React:
Passing data among siblings. This can be achieved by one of the following methods:
a. Integrating the methods mentioned above
b. Using Redux
c. Utilizing React's Context API.
Read the rest of this guide to better understand these concepts and learn how to implement them.
Try to imagine the directory structure of the app as follows: the parent component actually renders the child components in the app.
1App
2 └── Parent
3 ├── Child1
4 └── Child2
This is the simplest and most basic direction of data flow in React.
1class Parent extends React.Component {state = { data : "Hello World" }
2render() {
3
4 return (
5 <div>
6 <Child1/> //no data to send
7 <Child2 dataFromParent = {this.state.data} />
8 </div>
9 ); }
10}
11//Sending data as a state is not obligatory. You can use simple vars or const variables to pass data from parent to child.
Use the variable this.props.dataFromParent
to obtain the data passed from parent to child.
1class Child2 extends React.Component {
2 render() {
3
4 return (
5 <div>
6 Data from parent is:{this.props.dataFromParent}
7 </div>
8 );
9 }
10 }
Say you want to send a message from child1
to parent
withthe message "Hello, how are you?" Take the following steps:
1class Parent extends React.Component {
2state = { message: "" }
3callbackFunction = (childData) => {
4 this.setState({message: childData})
5},
6
7
8 render() {
9 return (
10 <div>
11 <Child1 parentCallback = {this.callbackFunction}/>
12 <p> {this.state.message} </p>
13 </div>
14 );
15}
16}
this.props.callback(dataToParent)
in the child1.js.1class Child1 extends React.Component{sendData = () => {
2 this.props.parentCallback("Hey Popsie, How’s it going?");
3 },
4
5render() {
6//Any time you wish to send data from child to parent component, call the sendData function.
7 }
8};
Choosing a method to share data among sibling can be a bit tricky for beginners. This guide covers three popular methods. After you read about them all, you can choose a favorite.
Method 1: Integrate the methods mentioned above .
Despite being a simple method, this does not work for complex directory structures. You might need to do extensive coding to send data between components that are several levels away from each other. Your data then travels back and forth across every intermediate level.
Method 2: Use Redux by maintaining the states of all child components that you might need in a global store and obtain the data from said store.
Method 3: Utilize React's Context API.
Recently, many developers are choosing React's Context API over Redux because the former saves them from prop-drilling. Prop-drilling is a common name for the process of passing down variables to subcomponents. The primary concept is passing the parameters to the following function as you move on.
Take a look the following directory structure that you need to pass data back and forth between Child1
and Child2
. In this example, assume that you need to send "How are you?" from Child1
to Child2
.
1App
2├── Child1
3└── Child2
This can be done using Context API as follows:
Step 1: Generate a provider component for the two child components.
The major objectives of this provider are:
contextObject.Provider
JSX componentStep 2: Inside the provider component, pass the state and callback mentioned above as props to all child components.
1export const MContext = React.createContext(); //exporting context object
2class MyProvider extends Component {
3state = {message: ""}
4render() {
5 return (
6 <MContext.Provider value={
7 { state: this.state,
8 setMessage: (value) => this.setState({
9 message: value })}}>
10 {this.props.children} //this indicates that all the child tags with MyProvider as Parent can access the global store.
11 </MContext.Provider>)
12 }
13}
You can think of the provider as the one in control of its children. This includes the global store of every state as well as the callback functions in charge of handling these states. Thus, any component that needs anything must contact the provider in order to access the objects.
In other words:
Child1
to create or edit the message, it must contact the provider and set its states.Child2
to view the data, it must access the provider and obtain its states.Step 3: Set the MyProvider
component as a parent to the two child components, Child1
and Child2
.
1class App extends React.Component {
2render() {
3 return (
4 <div>
5 <MyProvider>
6 <div className="App">
7 <Child1/>
8 <Child2/>
9 </div>
10 </MyProvider>
11 </div>
12 );
13}
14}
Step 4: Proceed accordingly, using ContextObject.Consumer
as illustrated below:.
Since Child1
and Child2
are both set as consumers of the provider, they can access the provider within consumer tags.
1import MContext
2class Child1 extends React.Component {
3render() {
4 return (
5 <div>
6 <Mcontext.Consumer>
7 {(context) => (
8 <button onClick={()=>{context.setMessage("New Arrival")}}>Send</button>
9 )}
10 </Mcontext.Consumer>
11 </div>
12 ) }
13}
Now Child2
can receive the data by accessing the provider within the consumer tags.
1import MContext
2class Child2 extends React.Component {
3render() {
4 return (
5 <div>
6 <Mcontext.Consumer>
7 {(context) => (
8 <p>{context.state.message}}</p>)}
9 </Mcontext.Consumer>
10 </div>
11 )}
12}
This guide covered how to pass data between different components in React in three ways: parent to child, child to parent, and between siblings. It also covered three popular methods for passing data between siblings. You can experiment and use the one that suits your need
Explore these React courses from Pluralsight to continue learning: