β 1. Parent to Child (via props)
π You simply pass data as a prop to the child.
function Parent() {
return <Child message="Hello from Parent!" />;
}
function Child({ message }) {
return <p>{message}</p>;
}
β 2. Child to Parent (using callback function)
π The parent passes a function as a prop, and the child calls it with data.
function Parent() {
const handleData = (childData) => {
console.log("Received from child:", childData);
};
return <Child sendData={handleData} />;
}
function Child({ sendData }) {
return (
<button onClick={() => sendData("Data from Child")}>
Send to Parent
</button>
);
}
β 3. Sibling to Sibling (via common parent)
π Use the parent to manage shared state and pass it to both children.
function Parent() {
const [data, setData] = useState("");
return (
<>
<SiblingA setData={setData} />
<SiblingB data={data} />
</>
);
}
function SiblingA({ setData }) {
return (
<button onClick={() => setData("Shared from Sibling A")}>
Send to Sibling B
</button>
);
}
function SiblingB({ data }) {
return <p>Received: {data}</p>;
}