Blog>
Snippets

Property Binding to Child Components

Explores how to pass data from a parent component to a child component using property binding, with the child component updating when the parent's data changes.
// ParentComponent.js
import React, { useState } from 'react';
import ChildComponent from './ChildComponent';

function ParentComponent() {
  // State in the parent component that we want to share with the child
  const [parentData, setParentData] = useState('Hello from Parent!');

  return (
    <div>
      <ChildComponent sharedProp={parentData} />
      {/* Property binding: sharedProp is bound to parentData */}
    </div>
  );
}
This is a parent component that includes a child component. It passes its state 'parentData' to the child component as a prop called 'sharedProp'. When 'parentData' changes, the ChildComponent will receive the new value through the 'sharedProp'.
// ChildComponent.js
import React from 'react';

function ChildComponent(props) {
  return <div>{props.sharedProp}</div>;
  // The child component receives the parent data through props.sharedProp
}
This is the child component that accepts props. The 'sharedProp' prop passed down from the parent component is accessed and displayed within a div.