Get Even More Visitors To Your Blog, Upgrade To A Business Listing >>

How to Pass Data from Child Component to Parent Component in React

How to Pass Data from One Component to Other Component in React?
Propsare used for passing data between the components. We usually use it to pass data from the Parent component to the child component. You should check out -What if we need to pass data from Parent to Child Component???

What if we need to pass data from Child to Parent Component???
If you are not using any state management library like Redux or React ContextAPI and you need to pass the data from child component to parent component.

UseCase  -
When clicking on any user rows, Implement functionality to get that user row data from the state data and display on page.

Solution- Use Props as callback functions.

Let’s see an Example,

I have created two components one is – Parent Component as DisplyList.js and other one is – Child Component as UserListItem.js.

Parent Component - DisplyList.js
import React from 'react'
import ListItem from '../src/listItem'

export class DisplyList extends React.Component {

    // Set dummy data
    state = {
        data: [{ id: 1name: 'Anil'email: '[email protected]' },
        { id: 2name: 'Aradhya'email: '[email protected]' }
        ]
    }

    //This is the row data from ChildComponent
    getUserData = (userRowData=> {
        console.log(userRowData);
    }

    render() {
        return (
            div>
                {
                    this.state.data.map((useri=> (
                        ListItem userRowData={user} handleClick={this.getUserData} key={i} />
                    ))
                }
            div>
        );
    }
}

export default DisplyList;




Child Component - UserListItem.js
import React from 'react';

const UserListItem = (props=> {
    return (
        // Using Props handleClick as callback function
        div onClick={() => props.handleClick(props.userRowData)}>
            div> ({props.userRowData.id}) : Name : {props.userRowData.name}, Email : {props.userRowData.email}div>
        div>
    );
}
export default UserListItem;


The above example code show how you can pass data from the Child to Parent component.

If you find any error, please feel free to correct it by commenting on it. I’m still learning and documenting what I learn.


This post first appeared on Programming, please read the originial post: here

Share the post

How to Pass Data from Child Component to Parent Component in React

×

Subscribe to Programming

Get updates delivered right to your inbox!

Thank you for your subscription

×