How to Pass Data from Child Component to Parent Component with React?

I think this is one of the most asked questions when you are on the learning path to React. Since React is unidirectional, it’s not possible to pass data from child component to parent component directly. It doesn’t mean that your child component can’t communicate with the parent component. You can still achieve this by passing a function as props from the parent component. Before move on to this, if you need clarification for passing data as props from the parent to the child then you can refer here. Now, we can pick an example.

First of all, we can create our child component with a button Click Me.

const ChildComponent = props => {

    return(
        <div>
            <button>Click Me</button>
        </div>
    )
}

Now, we can create our parent component where we will be calling the above component.

const ParentComponent = () => {

    const clickHandle = data => {
        console.log('Message from my child component is', data)
    }

    return(
        <div>
            <ChildComponent clickHandle={clickHandle}/>
        </div>
    )
}

Here, we have a function clickHandle which we pass as a prop to our child component. This function will receive an argument such that we can get data from the child. Now, we can modify our button in the child component as below.

<button
onClick={() => props.clickHandle('This is my message from child component')}>
Click Me
</button>

Now, we have successfully passed the message ‘This is my message from child component‘ to our parent from the child. By this way, you can also update the state of the parent from the child component. You can refer the full code below.

Final Code

Child Component
import React from "react"

const ChildComponent = props => {

    return(
        <div>
            <button
            onClick={() => props.clickHandle('This is my message from child component')}>
            Click Me
            </button>
        </div>
    )
}

export default ChildComponent
Parent Component
import React from 'react';
import ChildComponent from './child';

const ParentComponent = () => {

    const clickHandle = data => {
        console.log('Message from my child component is', data)
    }

    return(
        <div>
            <ChildComponent clickHandle={clickHandle}/>
        </div>
    )
}

export default ParentComponent

Similar Posts

Leave a Reply