Props
Props, short for “properties,” are a key concept in React.js used to pass data from one component to another, typically from a parent component to a child component. Props are immutable, meaning they are read-only and cannot be modified by the receiving component. Here’s a deeper look at how props work and why they are essential:
Key Characteristics of Props
- Data Transfer: Props are used to pass data and event handlers to child components, enabling dynamic and reusable UI components.
- Read-Only: Once a prop is passed to a component, it cannot be changed by that component. This ensures a unidirectional data flow and makes the application more predictable and easier to debug.
- Function Arguments: In functional components, props are passed as an argument to the function, while in class components, they are available via
this.props
.
Example of Using Props
Functional Component
Here’s an example of passing props to a functional component:
import React from 'react';
function Greeting(props) {
return <h1>Hello, {props.name}!</h1>;
}
function App() {
return <Greeting name="Alice" />;
}
export default App;
In this example:
- The
App
component passes a prop calledname
with the value"Alice"
to theGreeting
component. - The
Greeting
component receives thename
prop and uses it to render a personalized greeting.
Class Component
Here’s an example using a class component:
import React, { Component } from 'react';
class Greeting extends Component {
render() {
return <h1>Hello, {this.props.name}!</h1>;
}
}
class App extends Component {
render() {
return <Greeting name="Alice" />;
}
}
export default App;
In this example:
- The
App
class component passes thename
prop to theGreeting
class component. - The
Greeting
class component accesses thename
prop usingthis.props
.
Props with Default Values
We can also set default values for props using defaultProps
:
function Greeting(props) {
return <h1>Hello, {props.name}!</h1>;
}
Greeting.defaultProps = {
name: 'Guest',
};
function App() {
return <Greeting />;
}
export default App;
In this example, if the name
prop is not provided, the Greeting
component will use 'Guest'
as the default value.
Why Props Are Important
- Reusability: Props make components reusable by allowing them to receive dynamic data.
- Separation of Concerns: Props help separate the component logic from the component presentation.
- Unidirectional Data Flow: Props enforce a one-way data flow, which helps in maintaining the application’s state predictability.
Props are an essential part of React.js, enabling us to create dynamic, flexible, and reusable components.