In React, props (short for "properties") are used to pass data from a parent component to a child component. Here's how you can pass props to a React component:
Parent Component: In the parent component, when you render the child component, you can pass props as attributes.
jsximport React from 'react';
import ChildComponent from './ChildComponent';
const ParentComponent = () => {
const data = 'Hello from Parent!';
return (
<ChildComponent message={data} />
);
}
export default ParentComponent;
Child Component:
In the child component, you can access the passed props using the props
object.
jsximport React from 'react';
const ChildComponent = (props) => {
return (
<div>
<p>{props.message}</p>
</div>
);
}
export default ChildComponent;
In this example, the message
prop is passed from the ParentComponent
to the ChildComponent
. The child component then uses props.message
to access and render the passed data.
Keep in mind that props are read-only, meaning that a child component cannot modify the props it receives from its parent. If the child component needs to modify the data, it should communicate with its parent through callback functions.
Here's an example of passing a function as a prop to handle an event in the child component:
Parent Component:
jsximport React from 'react';
import ChildComponent from './ChildComponent';
const ParentComponent = () => {
const handleButtonClick = () => {
console.log('Button clicked in Parent!');
};
return (
<ChildComponent onButtonClick={handleButtonClick} />
);
}
export default ParentComponent;
Child Component:
jsximport React from 'react';
const ChildComponent = (props) => {
return (
<button onClick={props.onButtonClick}>
Click me
</button>
);
}
export default ChildComponent;
In this example, the onButtonClick
prop is a function passed from the parent to the child. The child component uses this function as an event handler for a button click.