Understanding React Props
A Beginner's Guide to Passing, Destructuring, Default Props, and Best Practices in Using Props in React
What are React Props?
In React, props are a way to pass data from a parent component to a child component.
The arguments we pass to functions are called "props" in React Components. It is an object which stores the value of attributes of a tag and gives a way to pass data from one component to other component. You can pass any type of data available in JavaScript — such as number
, Boolean
, or object
— into props.
Props in simple terms are used for communication among components in React app. Props or "properties" are the information that you pass to a JSX tag. For example, className
, src
, alt
, width
, and height
are some of the props you can pass to an <img>
tag. They allow you to customize the behavior and appearance of a component without modifying its code.
Note: React Props are read-only! You will get an error if you try to change their value.
Passing Props
In this example, we will be passing two props to the Welcome
component - name
and age
. Inside the Welcome
component, we access each prop value using props.name
and props.year
and wrap them in curly braces {}
.
import React from 'react';
function Welcome(props) {
return (
<div>
<h2>React was invented by {props.name}!</h2>
<p>It was initially released in {props.year}.</p>
</div>
);
}
export default Welcome;
Next, inside the App.jsx
file, we import the Welcome
Component and pass on the prop values as "Jordan Walke" and "2013" respectively.
import React from 'react';
function App() {
return (
<div>
<Welcome name="Jordan Walke" year={2013} />
</div>
);
}
export default App;
Let's checkout the output:
Destructuring Props
Destructuring, an ES6 feature, is a JavaScript feature that allows us to extract multiple pieces of data from an array or object and assign them to their own variables.
There are two ways to destructure props in a functional component:
- The first way is destructuring props in the function body:
import React from 'react'
function Employee (props) {
const {firstName, lastName, emailId} = props;
return (
<div>
<h1> Employee Details</h1>
<h2> First Name : {firstName} </h2>
<h2> Last Name : {lastName} </h2>
<h2> Eamil Id : {emailId} </h2>
</div>
)
}
export default Employee
- The second way is destructuring it in the function parameter itself:
import React from 'react'
function Employee ({firstName, lastName, emailId}) {
return (
<div>
<h1> Employee Details</h1>
<h2> First Name : {firstName} </h2>
<h2> Last Name : {lastName} </h2>
<h2> Eamil Id : {emailId} </h2>
</div>
)
}
export default Employee
Both methods of destructuring props in React are valid and widely used. I personally prefer the first option. Destructuring props directly in the function parameter makes the code more concise and easier to read.
Default Props
In React, defaultProps
is a feature that allows you to set default values for the props of a component. This ensures that your component can handle different usage scenarios, and provides a fallback for missing props.
Let's check an example:
import React from 'react';
function MyApp(props) {
const { name, age, occupation } = props;
return (
<div>
<h2>{name}</h2>
<p>Age: {age}</p>
<p>Occupation: {occupation}</p>
</div>
);
}
MyApp.defaultProps = {
name: 'Rajarshi',
age: 28,
occupation: 'Front-End Developer'
};
export default MyApp;
Here, MyApp
is a functional component that expects name
, age
, and occupation
as props. Now, import the component in App.jsx
and, if we pass the props:
<MyApp name="Alice" age={31} occupation="Full-Stack Developer" />
This will be the expected output:
However, if any of these props are not passed to the component, React will use the default values defined in the defaultProps
object:
Best practices
Keep props simple:
Each prop passed between components should have a clear purpose and be focused on a specific functionality. This will make your components more reusable and easier to maintain.
Use destructuring for props:
Destructuring props can make your code more concise and easier to read.
Use default props:
Define default values for props . This helps in situations where a prop value may not be available or is optional.
Avoid mutating props:
Avoid modifying props directly in a component as it can lead to unexpected behavior.
Validate props with PropTypes:
Use PropTypes to ensure that the data types of props are passed correctly and catch errors early in the development process.
Use meaningful prop names:
Meaningful and descriptive names for props can go a long way to make your code more readable and self-documenting.
To Summarize
Understanding how to use props effectively is an important aspect of building React applications. By passing props between components, you can create dynamic and reusable UI components that can be easily maintained and updated.
Destructuring props allows for cleaner code and better readability, while default props provide a safety net to prevent errors when certain props are not passed down.
By following best practices such as avoiding direct manipulation of props and using meaningful prop names, you can ensure that your React applications are efficient and scalable.
References
Thank's for taking the time to read this blog. Hope you found it informative and enjoyable!
In the next article of this series, we'll take a look at Conditional Rendering.
Catch you guys on the next one. Cheers .. ✌️