In React, you can pass data from a parent component to a child component by using props. Props (short for "properties") allow you to pass data from a parent component to a child component, making it accessible within the child component. Here's how you can do it:
In the Parent Component:
you define the child component and specify the data you want to pass as props. Here's an example of a parent component passing a string to a child component:
In the Child Component:
you can access the data passed from the parent component through the props object. Here's how you can access and use the data in the child component:
Note: Mouse hover on the code to copy
import React from 'react';
import ChildComponent from './ChildComponent';
function ParentComponent() {
const dataToPass = "Hello from the parent component";
return (
);
}
export default ParentComponent;
import React from 'react';
function ChildComponent(props) {
return (
Data from parent: {props.data}
);
}
export default ChildComponent;