How to Pass Data from Parent Component to Child Component

This post is for beginners who struggle to understand the data flow of React JS. You can pass data from a parent component to the child component as props. Props are like a variable which you can pass from one component to another. First of all, you can create a child component.

Child Component

import React from 'react'

function ChildComponent(props){
    return(
        <div>
            <h1>Hello, I am child component</h1>
        </div>
    )
}
export default ChildComponent

Now you can call this child component from a parent component.

Parent Component

import React from 'react'
import ChildComponent from './childComponent'

function ParentComponent(props){
    return(
        <div>
            <h1>Hello, I am parent component</h1>
            <ChildComponent/>
        </div>
    )
}
export default ParentComponent

Output

Now, it’s time for you to pass data from the parent component and render those content in the child component. You can refactor the code from parent component like this.

import React from 'react'
import ChildComponent from './childComponent'

function ParentComponent(props){
    return(
        <div>
            <ChildComponent message="A message from parent component"/>
        </div>
    )
}
export default ParentComponent

Here, message is the props passed from the parent component. Now, you can change the child component as follows.

import React from 'react'

function ChildComponent(props){
    return(
        <div>
            <h1>Hello, I am child component</h1>
            <h1>Message- {props.message}</h1>
        </div>
    )
}
export default ChildComponent

You can access the props object as an argument to the function. The output will be as follows

From this post, you’ve seen how to pass props from one component to another. You can pass any javascript data types as props to another component. Please note that props are unidirectional and read-only data, you can pass data from a parent component to child component but it’s not possible to pass data from a child component to parent component.

One Comment on “How to Pass Data from Parent Component to Child Component”

Leave a Reply