Blog>
Snippets

Functional Parent to Class Child Communication

Demonstrate the communication between a functional parent component and a class-based child component via props.
import React, { Component } from 'react';

// Define a Class-based Child Component
class ChildComponent extends Component {
    render() {
        // Child receives the props from the Parent
        const { messageFromParent } = this.props;

        return (
            <div>
                <h1>Child Component</h1>
                <p>Message from parent: {messageFromParent}</p>
            </div>
        );
    }
}
This is the ChildComponent which is class-based. It receives props from the parent component and renders the message contained within those props.
import React from 'react';
import ChildComponent from './ChildComponent';

// Define a Functional Parent Component
const ParentComponent = () => {
    const message = 'Hello from Parent!';

    return (
        <div>
            <h1>Parent Component</h1>
            {/* The message is passed down to the ChildComponent as a prop */}
            <ChildComponent messageFromParent={message} />
        </div>
    );
};

export default ParentComponent;
This is the ParentComponent which is functional. It defines a message and passes it down to the ChildComponent via props.