Introduction to Props in React JS
Props (short for properties) are one of the fundamental concepts in React JS. They allow components to receive data and configuration from their parent components. Props help developers create reusable, dynamic, and customizable UI components without duplicating code.
React JS Course: JustAcademy React JS Training Course
Course Demo: Register for React JS Course Demo
1. What Are Props in React?
Props are inputs passed from one React component to another. A parent component provides props to a child component through JSX attributes. The child component receives these values and uses them to determine what content or UI to display.
Props work similarly to arguments passed to a JavaScript function. They allow the same component to display different information depending on the values it receives.
Example
function Greeting(props) {
return <h1>Hello, {props.name}!</h1>;
}
function App() {
return <Greeting name="Manish" />;
}
export default App;
Output: Hello, Manish!
In this example, App passes the name prop to Greeting. The child component reads the value using props.name and displays it.
2. Why Are Props Important?
Props make React components flexible and reusable. Instead of creating a separate component for every piece of content, developers can create one component and pass different values whenever it is used.
- Reusability: Use the same component in multiple places with different data.
- Customization: Change the appearance or content of a component through its inputs.
- Data sharing: Pass information from parent components to child components.
- Maintainability: Reduce repeated JSX and make updates easier.
- Component composition: Combine smaller components to build larger interfaces.
- Dynamic interfaces: Display different information based on data supplied by the parent.
3. How Do Props Work?
Props generally flow from parent components to child components. The parent supplies values in JSX, and the child receives them as a props object.
Steps Involved
- Create a child component.
- Define the information the child component needs.
- Pass values to the child through JSX attributes.
- Receive the values inside the child component.
- Use the values to render the UI.
Example
function Student(props) {
return (
<div>
<h2>{props.name}</h2>
<p>Course: {props.course}</p>
</div>
);
}
function App() {
return (
<div>
<Student name="Aarav" course="React JS" />
<Student name="Priya" course="JavaScript" />
</div>
);
}
export default App;
Output:
Aarav
Course: React JS
Priya
Course: JavaScript
The same Student component is reused twice with different prop values. React renders different content for each instance.
4. Passing Props to a Component
Props are passed by adding attributes to a component's JSX tag. String values can be written inside quotation marks, while JavaScript expressions are enclosed in curly braces.
Passing a String
function Welcome({ name }) {
return <h1>Welcome, {name}!</h1>;
}
function App() {
return <Welcome name="Rahul" />;
}
Passing a Number
function Product({ price }) {
return <p>Price: ₹{price}</p>;
}
function App() {
return <Product price={999} />;
}
Passing a Boolean
function Status({ isAvailable }) {
return (
<p>
{isAvailable ? "Available" : "Unavailable"}
</p>
);
}
function App() {
return <Status isAvailable={true} />;
}
Passing a JavaScript Variable
function App() {
const userName = "Ananya";
return <Welcome name={userName} />;
}
Use quotation marks for string literals and curly braces when passing numbers, Boolean values, variables, function calls, objects, arrays, or other JavaScript expressions.
5. Receiving Props Inside a Component
A function component receives its props as its first argument. You can access individual values through the props object or use destructuring to extract the values you need.
Method 1: Using the Props Object
function Employee(props) {
return (
<div>
<h2>{props.name}</h2>
<p>Role: {props.role}</p>
</div>
);
}
Method 2: Using Destructuring
function Employee({ name, role }) {
return (
<div>
<h2>{name}</h2>
<p>Role: {role}</p>
</div>
);
}
Both methods work correctly. Destructuring is commonly used because it makes the code shorter and clearly identifies the props used by the component.
6. Different Types of Props
React props can carry many types of JavaScript values. They are not limited to strings or numbers.
| Prop Type |
Example |
Usage |
| String |
name="Aarav" |
Names, labels, titles. |
| Number |
age={22} |
Age, price, quantity. |
| Boolean |
isActive={true} |
Conditions and status. |
| Array |
items={["HTML", "CSS"]} |
Lists and collections. |
| Object |
user={{ name: "Aarav" }} |
Related information grouped together. |
| Function |
onClick={handleClick} |
Callbacks and event communication. |
| JSX |
icon={<span>★</span>} |
Passing UI elements as values. |
| Children |
<Card>Content</Card> |
Passing nested content to a component. |
7. Passing Multiple Props
A component can receive several props at the same time. Each prop provides a separate piece of information or configuration.
Example
function UserProfile({ name, age, city, profession }) {
return (
<section>
<h2>{name}</h2>
<p>Age: {age}</p>
<p>City: {city}</p>
<p>Profession: {profession}</p>
</section>
);
}
function App() {
return (
<UserProfile
name="Riya"
age={25}
city="Mumbai"
profession="Frontend Developer"
/>
);
}
This example demonstrates how multiple values can be passed to a single component to customize the information it displays.
8. Passing Objects as Props
Objects are useful when several related values belong together. Instead of passing each property separately, you can pass one object and access its properties inside the child component.
Example
function ProductDetails({ product }) {
return (
<div>
<h2>{product.name}</h2>
<p>Brand: {product.brand}</p>
<p>Price: ₹{product.price}</p>
</div>
);
}
function App() {
const productData = {
name: "Wireless Mouse",
brand: "TechPro",
price: 799
};
return <ProductDetails product={productData} />;
}
In this example, the entire productData object is passed through the product prop. The child component reads the object's properties to display product information.
Passing an Object Directly in JSX
<ProductDetails
product={{
name: "Keyboard",
brand: "KeyTech",
price: 1299
}}
/>
The outer curly braces indicate a JavaScript expression, and the inner braces create the object.
9. Passing Arrays as Props
Arrays can be passed to child components when the child needs to display a collection of items. The component can use array methods such as map() to render the data.
Example
function CourseList({ courses }) {
return (
<ul>
{courses.map((course) => (
<li key={course.id}>{course.name}</li>
))}
</ul>
);
}
function App() {
const courses = [
{ id: 1, name: "React JS" },
{ id: 2, name: "JavaScript" },
{ id: 3, name: "CSS" }
];
return <CourseList courses={courses} />;
}
The courses array is passed as a prop. The child component loops through the array and displays each course. Each rendered list item uses a stable key to help React track the items.
10. Default Values for Props
A default prop value is a fallback value used when a prop is missing or its value is undefined. In function components, default values can be provided through parameter destructuring.
Example
function Greeting({ name = "Guest" }) {
return <h1>Hello, {name}!</h1>;
}
function App() {
return (
<div>
<Greeting name="Aarav" />
<Greeting />
</div>
);
}
Output:
Hello, Aarav!
Hello, Guest!
When no name prop is provided, the component uses "Guest". If the prop is explicitly set to null, the default value will not be applied automatically.
More Default Value Examples
function Button({
label = "Click Me",
disabled = false,
variant = "primary"
}) {
return (
<button disabled={disabled} className={variant}>
{label}
</button>
);
}
11. Props Are Read-Only
Props should be treated as read-only inputs. A child component must not directly modify the props it receives. If the displayed information needs to change, the parent can provide new prop values, often by updating its own state.
Incorrect Example
function CounterDisplay(props) {
// Incorrect: do not modify a prop
props.count = props.count + 1;
return <p>Count: {props.count}</p>;
}
This code incorrectly attempts to modify a prop. React components should not mutate their props.
Correct Example
function CounterDisplay({ count }) {
return <p>Count: {count}</p>;
}
function App() {
return <CounterDisplay count={5} />;
}
The child component simply displays the supplied value. If the count needs to change, the parent should manage the changing value and pass the updated value down.
12. Props vs State
Props and state both influence what a component displays, but they serve different purposes. Props are supplied to a component by its parent, while state is data managed by a component or its owner that can change over time.
| Feature |
Props |
State |
| Meaning |
Inputs received from a parent. |
Data managed by a component or its owner. |
| Who provides or manages it? |
Usually the parent component provides the values. |
Usually managed using React state tools such as useState. |
| Can the child directly change it? |
No. Props should be treated as read-only. |
Update through the relevant state setter, not by direct mutation. |
| Purpose |
Customize a component and provide data. |
Represent changing data that affects rendering. |
| Example |
<Greeting name="Riya" /> |
const [count, setCount] = useState(0) |
Example Combining Props and State
import { useState } from "react";
function Counter({ initialCount = 0 }) {
const [count, setCount] = useState(initialCount);
return (
<div>
<p>Count: {count}</p>
<button onClick={() => setCount(count + 1)}>
Increase
</button>
</div>
);
}
export default function App() {
return <Counter initialCount={5} />;
}
Here, initialCount is a prop used to initialize the state. The changing count value is managed by the component using useState.
13. Passing Functions as Props
Props can contain functions. This is useful when a child component needs to notify a parent about an event, such as a button click or form submission. The parent passes a callback function, and the child calls it when appropriate.
Example
function ChildButton({ onMessage }) {
return (
<button onClick={onMessage}>
Send Message
</button>
);
}
function App() {
function handleMessage() {
alert("Message received!");
}
return <ChildButton onMessage={handleMessage} />;
}
export default App;
When the user clicks the button, the child component calls the function received through the onMessage prop.
Passing Arguments to a Callback
function UserButton({ onSelect, userId }) {
return (
<button onClick={() => onSelect(userId)}>
Select User
</button>
);
}
function App() {
function handleSelect(id) {
console.log("Selected user:", id);
}
return (
<UserButton userId={101} onSelect={handleSelect} />
);
}
Passing callbacks through props supports communication from a child to a parent without allowing the child to directly modify the parent's data.
14. The Children Prop
The special children prop contains content placed between a component's opening and closing tags. It allows developers to create reusable wrapper components such as cards, panels, dialogs, and layouts.
Example
function Card({ children }) {
return (
<div className="card">
{children}
</div>
);
}
function App() {
return (
<Card>
<h2>Welcome</h2>
<p>Learn React JS step by step.</p>
</Card>
);
}
The Card component does not need to know exactly which elements will be placed inside it. It receives the nested JSX as children and renders that content inside its wrapper.
15. Passing JSX and Components as Props
Props can carry JSX elements or component references. This allows one component to customize the content or visual elements displayed by another component.
Example: Passing an Icon
function ActionButton({ icon, label }) {
return (
<button>
{icon} {label}
</button>
);
}
function App() {
return (
<ActionButton
icon={<span aria-hidden="true">★</span>}
label="Favorite"
/>
);
}
The parent supplies an icon as JSX and a label as a string. The child combines them to create the button content.
16. Forwarding Props with the Spread Operator
The JSX spread syntax can forward several props to another component. It is useful when a component needs to pass along most or all of its received props without listing each one separately.
Example
function UserDetails({ name, city }) {
return (
<div>
<p>Name: {name}</p>
<p>City: {city}</p>
</div>
);
}
function Profile(props) {
return <UserDetails {...props} />;
}
function App() {
return <Profile name="Riya" city="Mumbai" />;
}
The expression {...props} forwards the properties to UserDetails. Use this technique selectively; explicitly listing props can make data flow easier to understand.
17. Common Mistakes When Using Props
| Mistake |
Why It Is a Problem |
Correct Approach |
| Forgetting to pass a required value |
The child may render missing or unexpected information. |
Pass the required prop or define an appropriate fallback. |
| Using the wrong prop name |
The child receives undefined for the expected property. |
Keep the names consistent between parent and child. |
| Passing a number as a quoted string unintentionally |
The value has a different JavaScript type. |
Use curly braces for numeric values, such as age={20}. |
| Trying to modify props |
Props are read-only inputs. |
Update the owning component's state or provide new values from the parent. |
| Using an object without accessing its properties |
The UI may not display the intended data. |
Read values such as user.name. |
| Calling a callback during rendering unintentionally |
The function may execute before the user interacts with the UI. |
Pass the function or an event-handler callback, such as onClick={() => handleClick()}. |
| Overusing the spread operator |
It can make it harder to see which props are passed where. |
Prefer explicit props when they improve clarity. |
| Confusing props with state |
It can lead to incorrect data ownership and updates. |
Use props for inputs and state for data managed by the relevant component. |
18. Practical Project: Student Information Card
In this mini-project, create a reusable student card that receives a student's name, course, and score through props.
Step 1: Create StudentCard.jsx
export default function StudentCard({ name, course, score }) {
return (
<div className="student-card">
<h2>{name}</h2>
<p>Course: {course}</p>
<p>Score: {score}%</p>
</div>
);
}
Step 2: Use StudentCard in App.jsx
import StudentCard from "./StudentCard.jsx";
export default function App() {
return (
<main>
<h1>Student Dashboard</h1>
<StudentCard
name="Aarav"
course="React JS"
score={92}
/>
<StudentCard
name="Priya"
course="JavaScript"
score={88}
/>
</main>
);
}
Step 3: Add CSS (Optional)
.student-card {
padding: 16px;
margin: 12px 0;
border: 1px solid #cccccc;
border-radius: 8px;
}
.student-card h2 {
margin-top: 0;
}
Learning outcome: This project demonstrates how one component can display different information based on props. It also introduces component reuse, destructuring, numeric props, and separating UI code into files.
19. Interview Questions and Answers
Q1. What are props in React?
Answer: Props are inputs passed to a React component, usually from a parent component. They allow components to receive data and configuration.
Q2. What is the full form of props?
Answer: Props stands for properties.
Q3. Can props be changed inside a child component?
Answer: No. Props should be treated as read-only. The parent can provide updated props when its data changes.
Q4. What is the difference between props and state?
Answer: Props are inputs received from a parent, while state is data managed by a component or its owner and updated through React's state mechanisms.
Q5. Can a component receive multiple props?
Answer: Yes. A component can receive multiple props, including strings, numbers, objects, arrays, Boolean values, functions, and JSX.
Q6. What is props destructuring?
Answer: Destructuring extracts specific properties from the props object directly in the function parameter, for example, function User({ name, age }).
Q7. What are default props in a function component?
Answer: They are fallback values that can be specified in parameter destructuring, such as function Greeting({ name = "Guest" }).
Q8. What is the children prop?
Answer: The children prop contains the nested content placed between a component's opening and closing JSX tags.
Q9. Can functions be passed as props?
Answer: Yes. Functions can be passed as callback props so a child can notify a parent about events or request an action.
Q10. What does the spread operator do when forwarding props?
Answer: JSX spread syntax, such as <Child {...props} />, forwards the properties from one props object to another component.
Q11. How do props support component reusability?
Answer: Props let the same component render different content or behavior based on the values supplied by its parent.
Q12. What happens if a prop is not provided?
Answer: The value is generally undefined unless a default value or another fallback is provided.
20. Practice Exercises
- Create a
Greeting component that receives a person's name through props.
- Create a
ProductCard component that accepts a product name, price, and category.
- Pass an array of course objects to a component and display them in a list.
- Use destructuring to receive multiple props.
- Set a default value for a missing prop.
- Create a button component that receives an event handler as a prop.
- Build a reusable
Card component that renders nested JSX through children.
- Create a student dashboard that displays multiple student cards using the same component.
21. Quick Revision Checklist
- Understand the meaning of props and properties.
- Know how to pass props through JSX attributes.
- Understand how to receive props in function components.
- Practice props destructuring.
- Know how to pass strings, numbers, Booleans, arrays, objects, and functions.
- Understand default prop values.
- Remember that props are read-only.
- Understand the difference between props and state.
- Know how callback functions can be passed as props.
- Understand the
children prop and JSX spread syntax.
- Build a small project using reusable components.
22. Conclusion
Props are a core concept in React JS because they enable parent components to pass information to child components. They make components reusable, customizable, and easier to maintain. By understanding how to pass and receive props, use destructuring, set default values, pass callbacks, and render nested content through children, developers can build flexible React applications with clear data flow.
To continue learning React JS, explore the JustAcademy React JS Training Course or register for a React JS course demo.
Official React Documentation