React components use properties (referred as "props") to pass data from one component to another, usually from a parent component to a child component. Props are read-only and immutable, meaning that a child component cannot modify them.
Props are passed from the parent component when the child component is rendered.
The child component can access these props and use them within its render method or any lifecycle methods.
Create a simple example to illustrate how props are used:
Parent Component:
import React from 'react';
import ChildComponent from './ChildComponent';
const ParentComponent = () => {
const message = "Hello from Parent!";
const number = 42;
return (
<div>
<h1>This is the Parent Component</h1>
<ChildComponent message={message} number={number} />
</div>
);
};
export default ParentComponent;
Child Component:
import React from 'react';
import PropTypes from 'prop-types';
const ChildComponent = ({ message, number }) => {
return (
<div>
<h2>This is the Child Component</h2>
<p>Message: {message}</p>
<p>Number: {number}</p>
</div>
);
};
ChildComponent.propTypes = {
message: PropTypes.string.isRequired,
number: PropTypes.number.isRequired
};
export default ChildComponent;
To make the code cleaner, you can use destructuring to extract props directly in the function parameters.
Child Component with Destructuring
import React from 'react';
const ChildComponent = ({ message, number }) => {
return (
<div>
<h2>This is the Child Component</h2>
<p>Message: {message}</p>
<p>Number: {number}</p>
</div>
);
};
export default ChildComponent;
To ensure that components receive the correct types of props, you can use PropTypes, which provides type-checking for props.
import React from 'react';
import PropTypes from 'prop-types';
const ChildComponent = ({ message, number }) => {
return (
<div>
<h2>This is the Child Component</h2>
<p>Message: {message}</p>
<p>Number: {number}</p>
</div>
);
};
ChildComponent.propTypes = {
message: PropTypes.string.isRequired,
number: PropTypes.number.isRequired
};
export default ChildComponent;