Props in React.js
In React.js, props
(short for properties) are a way to pass data from a parent component to a child component. They are a fundamental part of React’s component-based architecture and are used to make components reusable and customizable.
Here’s how props
work in React:
- Passing Props:
Parent components can pass data to child components by including attributes in the JSX markup when rendering the child component. These attributes are then accessible within the child component asprops
. Example:
// ParentComponent.js
import React from 'react';
import ChildComponent from './ChildComponent';
const ParentComponent = () => {
return <ChildComponent name="John" age={30} />;
};
export default ParentComponent;
// ChildComponent.js
import React from 'react';
const ChildComponent = (props) => {
return (
<div>
<p>Name: {props.name}</p>
<p>Age: {props.age}</p>
</div>
);
};
export default ChildComponent;
- Accessing Props:
Inside the child component, you can access the props passed from the parent component using theprops
object. Each prop passed by the parent is accessible as a property of theprops
object. Example:
const ChildComponent = (props) => {
return (
<div>
<p>Name: {props.name}</p>
<p>Age: {props.age}</p>
</div>
);
};
- Immutable Nature:
Props are immutable, meaning that they cannot be modified by the child component. They are read-only, and any changes to props should be managed by the parent component. - Default Props:
You can define default values for props using thedefaultProps
property. If a prop is not provided by the parent component, the default value will be used instead. Example:
const ChildComponent = (props) => {
return (
<div>
<p>Name: {props.name}</p>
<p>Age: {props.age}</p>
</div>
);
};
ChildComponent.defaultProps = {
name: 'Anonymous',
age: 0
};
Props play a crucial role in React development by enabling components to be customizable, reusable, and easily composed together to build complex user interfaces. They facilitate the flow of data throughout your application’s component hierarchy, making it easier to manage and maintain your code.