Pass Data from Child Component to Parent Component in React

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

How to Pass Data from One Component to Other Component in React?
Props are 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: 'anil.singh581@gmail.com' },
        { id: 2name: 'Aradhya'email: 'aradhya@gmail.com' }
        ]
    }

    //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.
ANIL SINGH

Anil Singh is an author, tech blogger, and software programmer. Book writing, tech blogging is something do extra and Anil love doing it. For more detail, kindly refer to this link..
My Blogs - https://code-sample.com and https://code-sample.xyz
My Book1 - BEST SELLING ANGULAR BOOK (INCLUDING ALL VERSIONS 2, 4, 5, 6, 7)
My Book2 - ANGULAR 2 INTERVIEW QUESTIONS BOOK - Both Books are Available on WorldWide.

www.code-sample.com/. Powered by Blogger.
^