React Props
By Codes With Pankaj
What Are Props in React?
Props (short for "properties") are used to pass data from one component to another in React. They make components reusable and dynamic by allowing you to customize their behavior or display based on the passed data.
Key Points About Props
Read-Only: Props cannot be modified by the component receiving them. They are immutable.
Passed From Parent to Child: Props are always passed down the component tree.
Accessible via
this.props
in Class Components orprops
in Functional Components.
Step-by-Step: Using Props in React
Step 1: Create a React App (if not already created)
If you don’t have a React app, create one with:
Step 2: Create a Simple Component to Use Props
Inside the
src
folder, create a new file calledGreeting.js
.Add the following code:
Explanation:
this.props.name
: Accesses thename
prop passed to theGreeting
component.this.props.platform
: Accesses theplatform
prop.
Step 3: Use the Component in App.js
Open
src/App.js
.Import the
Greeting
component:Use the
Greeting
component with props:
Step 4: Run the Project
Start the app:
You’ll see the following output in your browser:
How Props Work
Parent-to-Child Data Flow:
Props are passed from the parent component (
App
) to the child component (Greeting
).For example:
Accessing Props in the Child:
The
Greeting
component receivesname
andplatform
as props and accesses them usingthis.props.name
andthis.props.platform
.
Props in Functional Components
You can also use props in functional components. Here's how:
Modify
Greeting.js
to a functional component:The result in the browser will remain the same.
Default Props
You can define default values for props if they are not provided:
Update the
Greeting
component:Use the component without passing props:
Output:
Prop Validation
To ensure the correct data type for props, use PropTypes:
Install
prop-types
:Add PropTypes to
Greeting.js
:Explanation:
Ensures that
name
andplatform
are strings and required.If props are missing or incorrect, a warning will appear in the console.
Why Use Props?
Reusable Components: Pass different data to the same component.
Dynamic Content: Make components display different content based on input.
Maintainable Code: Keeps components simple and focused on rendering UI.
Congratulations! 🎉
You now understand how to use React Props to create dynamic and reusable components.
Stay tuned for more React tutorials on Codes With Pankaj! 😊
Last updated