In React, props
(short for properties) is a special keyword that stands for properties passed to React components. Props are used to pass data from one component to another, similar to how arguments work in functions. They are immutable and read-only within the component that receives them.
Table of Contents
Key Concepts of Props:
- Passing Data:
- Props allow you to pass data from a parent component to a child component.
- They enable communication between components in a React application.
- Immutable and Read-only:
- Once props are passed to a component, they cannot be modified by that component. They are considered immutable.
- This ensures data integrity and helps maintain the predictability of components.
- Usage:
- Props are accessed similar to function arguments within the component.
- They are specified in JSX using attributes and passed down through component hierarchies.
Example of Using Props:
Parent Component
import React from 'react';
import ChildComponent from './ChildComponent';
function ParentComponent() {
const name = 'Alice';
const age = 30;
return (
<div>
<ChildComponent name={name} age={age} />
</div>
);
}
Child Component
import React from 'react';
function ChildComponent(props) {
return (
<div>
<p>Name: {props.name}</p>
<p>Age: {props.age}</p>
</div>
);
}
Explanation:
- Parent Component: Passes
name
andage
as props toChildComponent
. - Child Component: Receives
name
andage
asprops
and displays them within its JSX.
Prop Types
While React does not enforce strict prop types by default, it’s good practice to document the expected props for each component using PropTypes or TypeScript (if using TypeScript).
PropTypes Example
import PropTypes from 'prop-types';
function ChildComponent(props) {
return (
<div>
<p>Name: {props.name}</p>
<p>Age: {props.age}</p>
</div>
);
}
ChildComponent.propTypes = {
name: PropTypes.string.isRequired,
age: PropTypes.number.isRequired,
};
Default Props
You can also define default values for props using defaultProps
in functional components or within the class component.
Default Props Example
function ChildComponent(props) {
return (
<div>
<p>Name: {props.name}</p>
<p>Age: {props.age}</p>
</div>
);
}
ChildComponent.defaultProps = {
name: 'Unknown',
age: 0,
};
When to Use Props:
- Component Composition: Use props to customize and configure child components within parent components.
- Dynamic Content: Pass data dynamically to render different UI based on props.
- Event Handling: Pass functions as props to handle events or callbacks from child to parent components.
Conclusion:
Props are a fundamental concept in React for passing data between components. They allow you to create reusable and modular components that can be easily configured and customized based on the data passed from their parent components. Understanding how to use props effectively is essential for building scalable and maintainable React applications.