In React, properties (commonly referred to as "props") are used to pass data from parent components to child components. Props are immutable, meaning they cannot be modified by the child component. Here’s a step-by-step guide on how to set and use props in React:
Create a child component that will receive props from the parent component.
Child Component Example
import React from 'react';
const ChildComponent = (props) => {
return (
<div>
<h2>{props.title}</h2>
<p>{props.description}</p>
</div>
);
};
export default ChildComponent;
In the parent component, you pass the props to the child component by including them as attributes in the child component tag.
Parent Component Example:
import React from 'react';
import ChildComponent from './ChildComponent';
const ParentComponent = () => {
return (
<div>
<ChildComponent title="Hello, World!"
description="This is a description passed from the parent component." />
</div>
);
};
export default ParentComponent;
In the child component, you can access the props using props.propertyName.
Using Destructuring
To make the code cleaner, you can destructure the props in the function parameter.
const ChildComponent = ({ title, description }) => {
return (
<div>
<h2>{title}</h2>
<p>{description}</p>
</div>
);
};
To ensure that the props passed to the component have the correct type and provide default values, you can use PropTypes and defaultProps.
Using PropTypes
First, install the prop-types package if it’s not already installed:
npm install prop-types
Then, define the prop types in your component.
import React from 'react';
import PropTypes from 'prop-types';
const ChildComponent = ({ title, description }) => {
return (
<div>
<h2>{title}</h2>
<p>{description}</p>
</div>
);
};
ChildComponent.propTypes = {
title: PropTypes.string.isRequired,
description: PropTypes.string,
};
ChildComponent.defaultProps = {
description: 'Default description if none is provided',
};
export default ChildComponent;