Passing Arrays and Objects in React
Course: React JS Training
Topic: Passing Arrays and Objects as Props in React
Learning Objective: Understand how to pass arrays and objects from parent components to child components, access their values through props, display dynamic data, render lists, work with nested objects, and build reusable React components.
1. Introduction to Passing Arrays and Objects
React components communicate with each other using props. Props allow a parent component to pass data to a child component. React supports passing different JavaScript values through props, including strings, numbers, booleans, arrays, objects, functions, and JSX elements.
Arrays and objects are especially useful when applications need to manage multiple related values. An array can store a list of products, students, courses, or tasks. An object can store related information about one person, product, employee, or course.
For example, a parent component can pass an array of course names to a child component and pass an object containing a student's name, age, and marks to another child component.
Basic example
function CourseList({ courses }) {
return (
<ul>
{courses.map((course, index) => (
<li key={index}>{course}</li>
))}
</ul>
);
}
function Student({ student }) {
return (
<div>
<h2>{student.name}</h2>
<p>Age: {student.age}</p>
</div>
);
}
function App() {
const courses = ["React JS", "JavaScript", "HTML and CSS"];
const student = { name: "Amit", age: 21 };
return (
<div>
<CourseList courses={courses} />
<Student student={student} />
</div>
);
}
export default App;
In this example, courses is an array and student is an object. Both values are passed from the parent component to child components using props.
2. What Is an Array in JavaScript?
An array is a JavaScript data structure that stores multiple values in a single variable. Arrays are useful when an application needs to work with a collection of related items.
Array values are written inside square brackets [] and separated by commas.
Example of an array
const courses = ["React JS", "JavaScript", "Node.js"];
const marks = [85, 90, 78, 92];
const colors = ["red", "green", "blue"];
Arrays can contain strings, numbers, objects, booleans, or a mixture of different JavaScript values.
Common uses of arrays in React
- Displaying a list of students.
- Rendering multiple product cards.
- Showing course names and categories.
- Displaying notifications or messages.
- Managing todo lists.
- Displaying menu items or navigation links.
- Working with data returned from an API.
3. What Is an Object in JavaScript?
An object is a JavaScript data structure that stores information as key-value pairs. Each key identifies a property, and its associated value stores the information.
Objects are written using curly braces {}. Property names and values are separated by colons, and properties are separated by commas.
Example of an object
const student = {
name: "Priya",
age: 22,
course: "React JS",
marks: 90
};
In this example, name, age, course, and marks are object properties.
Common uses of objects in React
- Storing user profile information.
- Displaying product details.
- Representing employee records.
- Storing course information.
- Managing application settings.
- Working with API responses.
- Grouping related information into one value.
4. Difference Between Arrays and Objects
| Feature |
Array |
Object |
| Purpose |
Stores an ordered collection of values. |
Stores related values as named properties. |
| Syntax |
Square brackets [] |
Curly braces {} |
| Access method |
Usually accessed by index. |
Usually accessed by property name. |
| Example |
["React", "JavaScript"] |
{name: "Amit", age: 21} |
| Access example |
courses[0] |
student.name |
| Typical use |
Lists of courses or products. |
Details of one course or product. |
5. Passing an Array to a React Component
To pass an array to a child component, define the array in the parent component and pass it through a prop using curly braces in JSX.
Example: Passing a list of courses
function CourseList({ courses }) {
return (
<div>
<h2>Available Courses</h2>
<ul>
{courses.map((course, index) => (
<li key={index}>{course}</li>
))}
</ul>
</div>
);
}
function App() {
const courses = ["React JS", "JavaScript", "Node.js"];
return <CourseList courses={courses} />;
}
export default App;
Expected output
Available Courses
- React JS
- JavaScript
- Node.js
Explanation:
- The parent component defines an array named
courses.
- The expression
courses={courses} passes the array as a prop.
- The child component receives the array through
{courses} destructuring.
- The
map() method creates a list item for every course.
- The
key prop helps React identify list items when rendering updates occur.
6. Passing an Array of Numbers
Arrays do not have to contain strings. They can also store numbers, which can be displayed, calculated, filtered, or sorted inside a component.
Example: Displaying student marks
function MarksList({ marks }) {
return (
<div>
<h2>Student Marks</h2>
<ul>
{marks.map((mark, index) => (
<li key={index}>{mark}</li>
))}
</ul>
</div>
);
}
function App() {
const marks = [85, 90, 78, 95];
return <MarksList marks={marks} />;
}
export default App;
Expected output
Student Marks
- 85
- 90
- 78
- 95
Example: Calculating the total of an array
function MarksSummary({ marks }) {
const total = marks.reduce((sum, mark) => sum + mark, 0);
const average = marks.length ? total / marks.length : 0;
return (
<div>
<p>Total Marks: {total}</p>
<p>Average Marks: {average.toFixed(2)}</p>
</div>
);
}
function App() {
return <MarksSummary marks={[80, 90, 85]} />;
}
export default App;
Output: Total Marks: 255; Average Marks: 85.00.
The reduce() method calculates the total by combining the values in the array. The length check prevents division by zero when the array is empty.
7. Passing an Array of Objects
In real-world React applications, arrays often contain objects rather than simple strings or numbers. For example, a list of products may contain each product's ID, name, price, and category.
Example: Product list
function ProductList({ products }) {
return (
<div>
<h2>Products</h2>
{products.map((product) => (
<div key={product.id}>
<h3>{product.name}</h3>
<p>Price: ₹{product.price}</p>
</div>
))}
</div>
);
}
function App() {
const products = [
{ id: 1, name: "Keyboard", price: 1200 },
{ id: 2, name: "Mouse", price: 650 },
{ id: 3, name: "Monitor", price: 8500 }
];
return <ProductList products={products} />;
}
export default App;
Expected output
Products
Keyboard
Price: ₹1200
Mouse
Price: ₹650
Monitor
Price: ₹8500
Explanation: The parent passes an array of product objects to ProductList. The child uses map() to create a section for each product. Each product's properties are accessed using expressions such as product.name and product.price.
Best practice: Use a stable, unique identifier such as product.id for each mapped item's key when one is available. Avoid using array indexes as keys when list items can be reordered, inserted, or deleted.
8. Passing an Object to a React Component
An object can be passed as a prop by placing the object expression inside JSX curly braces. The child component can then access its properties using dot notation or destructuring.
Example: Passing student details
function StudentProfile({ student }) {
return (
<div>
<h2>Name: {student.name}</h2>
<p>Age: {student.age}</p>
<p>Course: {student.course}</p>
</div>
);
}
function App() {
const student = {
name: "Anjali",
age: 21,
course: "React JS"
};
return <StudentProfile student={student} />;
}
export default App;
Expected output
Name: Anjali
Age: 21
Course: React JS
In this example, the student object is passed as one prop. The child component accesses its properties using student.name, student.age, and student.course.
9. Understanding Double Curly Braces in JSX
When passing an object literal directly in JSX, you will often see two pairs of curly braces. This syntax may look confusing at first, but each pair has a different purpose.
function App() {
return (
<StudentProfile
student={{
name: "Rahul",
age: 22,
course: "React JS"
}}
/>
);
}
In student={{ name: "Rahul", age: 22 }}:
- The outer curly braces tell JSX to evaluate a JavaScript expression.
- The inner curly braces define the JavaScript object literal.
- The object is passed as the value of the
student prop.
You can also define the object in a separate variable and pass that variable, which may be easier to read when the object contains many properties.
const student = {
name: "Rahul",
age: 22,
course: "React JS"
};
return <StudentProfile student={student} />;
10. Accessing Object Properties in a Child Component
There are several ways to access an object's properties after receiving it through props.
Method 1: Dot notation
function Employee({ employee }) {
return (
<div>
<p>Name: {employee.name}</p>
<p>Department: {employee.department}</p>
</div>
);
}
Method 2: Destructure the object inside the component
function Employee({ employee }) {
const { name, department } = employee;
return (
<div>
<p>Name: {name}</p>
<p>Department: {department}</p>
</div>
);
}
Method 3: Destructure nested props directly
function Employee({ employee: { name, department } }) {
return (
<div>
<p>Name: {name}</p>
<p>Department: {department}</p>
</div>
);
}
All three approaches can work. The first approach is often easiest for beginners, while the second makes frequently used properties convenient to access. Direct nested destructuring is concise, but it assumes the employee object exists.
11. Passing Nested Objects
An object can contain another object as one of its properties. This is called a nested object. Nested objects are useful for representing structured information such as a user's address, a product's specifications, or an employee's contact details.
Example: User profile with address
function UserProfile({ user }) {
return (
<div>
<h2>{user.name}</h2>
<p>Email: {user.email}</p>
<p>City: {user.address.city}</p>
<p>Country: {user.address.country}</p>
</div>
);
}
function App() {
const user = {
name: "Priya Sharma",
email: "[email protected]",
address: {
city: "Mumbai",
country: "India"
}
};
return <UserProfile user={user} />;
}
export default App;
Expected output
Priya Sharma
Email: [email protected]
City: Mumbai
Country: India
The nested properties are accessed using chained dot notation, such as user.address.city.
Important: If nested data might be missing, check that it exists before accessing its properties. For example, user.address?.city uses optional chaining to avoid an error if address is null or undefined.
12. Passing Arrays and Objects Together
A component can receive an array and an object at the same time. This is common when a page displays a profile alongside a list of activities, skills, or courses.
Example: Student profile and skills
function StudentDashboard({ student, skills }) {
return (
<div>
<h2>{student.name}</h2>
<p>Course: {student.course}</p>
<h3>Skills</h3>
<ul>
{skills.map((skill) => (
<li key={skill}>{skill}</li>
))}
</ul>
</div>
);
}
function App() {
const student = {
name: "Aman",
course: "Frontend Development"
};
const skills = ["HTML", "CSS", "JavaScript", "React"];
return (
<StudentDashboard student={student} skills={skills} />
);
}
export default App;
The student prop contains one object, while the skills prop contains an array of strings. The child component uses both to display the dashboard.
13. Rendering Arrays with the map() Method
The map() method is commonly used in React to transform array values into JSX elements. It runs a callback for every item and returns a new array of results.
Basic syntax
array.map((item, index) => {
return <li key={index}>{item}</li>;
});
Example: Rendering a list of tasks
function TaskList({ tasks }) {
return (
<ul>
{tasks.map((task) => (
<li key={task.id}>{task.title}</li>
))}
</ul>
);
}
function App() {
const tasks = [
{ id: 1, title: "Learn JSX" },
{ id: 2, title: "Practice props" },
{ id: 3, title: "Build a project" }
];
return <TaskList tasks={tasks} />;
}
export default App;
React renders one list item for each task. Using the task's unique ID as its key helps React track the items efficiently when the list changes.
14. Filtering and Sorting Arrays Passed Through Props
Arrays received through props can be used to create filtered or sorted views. These operations should not mutate the original array.
Example: Displaying affordable products
function AffordableProducts({ products }) {
const affordable = products.filter(
(product) => product.price <= 1000
);
return (
<ul>
{affordable.map((product) => (
<li key={product.id}>
{product.name} - ₹{product.price}
</li>
))}
</ul>
);
}
function App() {
const products = [
{ id: 1, name: "Mouse", price: 650 },
{ id: 2, name: "Keyboard", price: 1200 },
{ id: 3, name: "USB Cable", price: 250 }
];
return <AffordableProducts products={products} />;
}
export default App;
The filter() method returns a new array containing only products priced at ₹1,000 or less. The original array remains unchanged.
Example: Sorting products by price
function SortedProducts({ products }) {
const sortedProducts = [...products].sort(
(a, b) => a.price - b.price
);
return (
<ul>
{sortedProducts.map((product) => (
<li key={product.id}>
{product.name}: ₹{product.price}
</li>
))}
</ul>
);
}
The spread syntax [...products] creates a shallow copy before sorting. This prevents the original array from being reordered by sort().
15. Default Values for Array and Object Props
Components can define default values for optional array and object props. This helps prevent errors when a parent does not provide a value.
Example: Default array
function SkillList({ skills = [] }) {
return (
<ul>
{skills.map((skill) => (
<li key={skill}>{skill}</li>
))}
</ul>
);
}
function App() {
return <SkillList />;
}
export default App;
If skills is missing or undefined, the component uses an empty array. The map() method can then run safely.
Example: Default object
function UserCard({
user = { name: "Guest", city: "Unknown" }
}) {
return (
<div>
<h2>{user.name}</h2>
<p>City: {user.city}</p>
</div>
);
}
This default object is used when the user prop is missing or undefined. If user is explicitly null, the default does not apply, so the component should handle that case if it is possible in the application.
16. Passing Arrays and Objects from API Data
React applications frequently receive data from APIs. API responses commonly contain arrays of objects or individual objects. Once the data is available, it can be passed to child components using props.
Example: API-style product data
const products = [
{ id: 101, name: "Laptop", price: 55000 },
{ id: 102, name: "Headphones", price: 2500 },
{ id: 103, name: "Webcam", price: 1800 }
];
function ProductList({ products }) {
return (
<div>
{products.map((product) => (
<article key={product.id}>
<h2>{product.name}</h2>
<p>Price: ₹{product.price.toLocaleString("en-IN")}</p>
</article>
))}
</div>
);
}
function App() {
return <ProductList products={products} />;
}
export default App;
This example uses static data in an API-like structure. In a real application, the array may come from an API request. It is important to handle loading, error, and empty-data states when fetching data asynchronously.
17. Props Are Read-Only
Props should be treated as read-only inputs. A child component should not directly change an array or object received through props. Direct mutation can cause unexpected behavior because React relies on predictable data flow.
Incorrect approach
function ProductList({ products }) {
// Avoid mutating props:
// products.push({ id: 4, name: "Tablet", price: 20000 });
return <p>Total products: {products.length}</p>;
}
Safer approach: Create a new array
const updatedProducts = [
...products,
{ id: 4, name: "Tablet", price: 20000 }
];
If a child component needs to request a change, it can call a callback function supplied by the parent. If the component owns the changing data, React state can be used. Arrays and objects in state should also be updated immutably rather than mutated directly.
18. Common Mistakes When Passing Arrays and Objects
Mistake 1: Forgetting curly braces
// Incorrect if courses is a JavaScript variable:
<CourseList courses="courses" />
// Correct:
<CourseList courses={courses} />
The first version passes the literal string "courses". The second passes the variable containing the array.
Mistake 2: Forgetting to use map() for a list
// Incorrect: an array of objects is not directly rendered
// as a list of readable product cards.
<div>{products}</div>
// Correct:
{products.map((product) => (
<p key={product.id}>{product.name}</p>
))}
Mistake 3: Accessing a missing property
// May fail if user or address is missing:
user.address.city
// Safer when the data may be incomplete:
user?.address?.city
Optional chaining returns undefined if a part of the chain is null or undefined. It does not replace proper validation when required data must exist.
Mistake 4: Missing keys in mapped elements
// Avoid omitting the key:
products.map((product) => (
<li>{product.name}</li>
));
// Better:
products.map((product) => (
<li key={product.id}>{product.name}</li>
));
Mistake 5: Mutating an array while sorting
// Avoid sorting the original prop array:
products.sort((a, b) => a.price - b.price);
// Copy first:
const sorted = [...products].sort(
(a, b) => a.price - b.price
);
Mistake 6: Assuming nested data always exists
// Can fail if user.profile is missing:
user.profile.city
// Optional chaining:
user.profile?.city
19. Best Practices for Passing Arrays and Objects
- Use arrays for collections of items and objects for related named properties.
- Pass arrays and objects using JSX expressions, such as
items={items} and user={user}.
- Use meaningful prop names, such as
products, student, skills, or employee.
- Use
map() to render arrays into JSX elements.
- Provide stable unique keys for mapped elements.
- Use dot notation or destructuring to access object properties.
- Check for missing or optional nested properties when working with incomplete data.
- Use default props or parameter defaults when appropriate.
- Do not mutate arrays or objects received through props.
- Copy arrays before using mutating methods such as
sort().
- Validate API data before rendering or calculating with it.
- Keep components focused and reusable by passing only the data they need.
20. Practical Project: Student Management Cards
Project objective: Create reusable student cards using an array of student objects. Each object stores a student's name, course, age, and skills.
App.jsx
function StudentCard({ student }) {
return (
<article className="student-card">
<h2>{student.name}</h2>
<p>Age: {student.age}</p>
<p>Course: {student.course}</p>
<h3>Skills</h3>
<ul>
{student.skills.map((skill) => (
<li key={skill}>{skill}</li>
))}
</ul>
</article>
);
}
function StudentList({ students }) {
return (
<section>
<h1>Student Management</h1>
<div className="student-list">
{students.map((student) => (
<StudentCard key={student.id} student={student} />
))}
</div>
</section>
);
}
export default function App() {
const students = [
{
id: 1,
name: "Aarav",
age: 20,
course: "React JS",
skills: ["HTML", "CSS", "JavaScript"]
},
{
id: 2,
name: "Diya",
age: 22,
course: "Frontend Development",
skills: ["JavaScript", "React", "Git"]
},
{
id: 3,
name: "Kabir",
age: 21,
course: "Web Development",
skills: ["HTML", "CSS", "React"]
}
];
return <StudentList students={students} />;
}
App.css
body {
margin: 0;
padding: 24px;
font-family: Arial, sans-serif;
background: #f4f6f8;
}
.student-list {
display: grid;
grid-template-columns: repeat(auto-fit, minmax(220px, 1fr));
gap: 16px;
}
.student-card {
padding: 20px;
border: 1px solid #ddd;
border-radius: 10px;
background: #fff;
}
.student-card h2 {
margin-top: 0;
}
How the project works
- The parent component defines an array named
students.
- Each element of the array is an object containing student details.
- The parent passes the complete array to
StudentList.
StudentList maps over the array and renders a StudentCard for every student.
- Each
StudentCard receives one student object through its student prop.
- The student card displays object properties and maps over the nested skills array.
Project learning outcomes
- Pass an array of objects from a parent to a child component.
- Access object properties using props.
- Render lists with
map().
- Render nested arrays inside an object.
- Use unique IDs as React keys.
- Build reusable components with structured data.
21. Practice Exercises
- Create an array of five course names and pass it to a child component.
- Create a product object with a name, price, and category, then display its properties.
- Create an array of student objects and render each student's name and marks.
- Create a nested user object with an address and display the city and country.
- Pass an array of numbers and calculate its sum and average.
- Create a list of products and use
filter() to display products below ₹1,000.
- Sort a copied product array by price without modifying the original array.
- Create a skills array inside a student object and display each skill as a list item.
- Provide an empty array as the default value for a list prop.
- Build a course catalogue using an array of course objects, each with an ID, title, duration, and fee.
22. Interview Questions and Answers
Q1. Can React props contain arrays and objects?
Answer: Yes. Props can carry any JavaScript value, including arrays, objects, functions, and other values.
Q2. How do you pass an array to a component?
Answer: Define the array and pass it using JSX curly braces, for example <CourseList courses={courses} />.
Q3. How do you pass an object to a component?
Answer: Pass the object as a prop, for example <StudentProfile student={student} />.
Q4. Why are there double curly braces when passing an object literal?
Answer: The outer braces indicate a JavaScript expression in JSX, while the inner braces define the object literal.
Q5. How do you render an array in React?
Answer: Use the array's map() method to return JSX elements for each item and provide a suitable key for every mapped element.
Q6. How do you access an object property passed through props?
Answer: Use dot notation, such as student.name, or destructure the object to access its properties directly.
Q7. What is an array of objects?
Answer: It is an array in which each element is an object. It is commonly used to represent collections such as products, users, or students.
Q8. Why are keys important when rendering arrays?
Answer: Keys help React match list elements between renders, especially when items are added, removed, or reordered.
Q9. Should props be mutated inside a child component?
Answer: No. Props should be treated as read-only. Create a new array or object when a transformed value is needed, or use state and callbacks to manage changes.
Q10. How do you safely access nested object properties?
Answer: Use checks or optional chaining, such as user.address?.city, when a nested property may be missing.
Q11. What is the difference between map() and filter()?
Answer: map() transforms every array item into a corresponding result, while filter() returns only the items that satisfy a condition.
Q12. How can a component handle a missing array prop?
Answer: It can use a default value such as function List({ items = [] }), while separately handling explicit null values if they are possible.
23. Quick Revision Checklist
- Understand the difference between arrays and objects.
- Pass arrays and objects through JSX props.
- Use curly braces to pass JavaScript variables and expressions.
- Understand why object literals use double curly braces in JSX.
- Access object properties using dot notation or destructuring.
- Render arrays using
map() and stable keys.
- Work with arrays of objects and nested objects.
- Use
filter() and sort() without mutating props.
- Provide defaults and handle missing data safely.
- Remember that props are read-only.
24. Conclusion
Passing arrays and objects is an important React skill because applications often need to display collections of data and groups of related properties. Arrays are useful for lists, while objects are useful for structured records. React props make it possible to pass these values from parent components to child components and reuse the same UI for different data.
By practising with course lists, product cards, student records, and nested user profiles, you can learn to pass structured data, render dynamic lists, access nested properties, and build reusable components. Always use stable keys for mapped elements and avoid mutating props.
25. React JS Training Resources
Explore the following course and learning resources: