💻Lecture Notes of Class 8
Lists and Keys
Objective
By
the end of this class, students will be able to:
- Understand how to display lists
dynamically using the map() function.
- Understand the importance of
keys in rendering lists efficiently.
- Render dynamic lists from arrays.
Topics Covered
1.
What
is map()?
2.
Rendering
lists dynamically using map()
3.
Why
are keys important in lists?
4.
Dynamic
list rendering in React
1. What is map()?
- map() is a built-in JavaScript
array method.
- It creates a new array
by applying a function to each element of an existing array.
- Syntax:
let newArray = oldArray.map((element,
index) => {
// return something for newArray
});
- Example:
const numbers = [1, 2, 3];
const doubled = numbers.map(num
=> num * 2);
console.log(doubled); // Output: [2,
4, 6]
2. Rendering Lists Dynamically Using
map()
In
React (or any similar library), instead of writing HTML for each item manually,
you can use map() to generate components dynamically from an array.
Example:
Suppose we have an array of products:
const products = ['Apple', 'Banana',
'Orange'];
Instead of:
<ul>
<li>Apple</li>
<li>Banana</li>
<li>Orange</li>
</ul>
We can write:
<ul>
{products.map(product => (
<li>{product}</li>
))}
</ul>
3. Why Are Keys Important in Lists?
- Keys help React identify
which items have changed, are added, or removed.
- They improve performance
by enabling efficient updates.
- Keys must be unique among
siblings but don't need to be globally unique.
- Usually, keys are derived from
unique IDs in your data.
Example with keys:
<ul>
{products.map((product, index) => (
<li key={index}>{product}</li>
))}
</ul>
Note: Using index as a key is okay for
static lists but not recommended for dynamic or reordered lists.
4. Dynamic List Rendering in React
Let's
render a list of products dynamically using React components.
import React from 'react';
const products = ['Apple', 'Banana', 'Orange'];
return (
<div>
<h2>Product List</h2>
<ul>
{products.map((product, index) => (
<li key={index}>{product}</li>
))}
</ul>
</div>
);
}
export default ProductList;
Activity: Render a List of Products
from an Array
Task: Create a React component that
renders a list of product names from the following array:
const products = ['Laptop', 'Smartphone', 'Tablet', 'Monitor'];
Steps:
1.
Use
the map() function to loop through the array.
2.
Display
each product name inside an <li> element.
3.
Assign
a unique key to each list item.
Homework
1.
Add
prices:
Update the product array to include prices as objects, e.g.,
const products = [
{ name: 'Laptop', price: 900 },
{ name: 'Smartphone', price: 600 },
{ name: 'Tablet', price: 300 },
{ name: 'Monitor', price: 200 }
];
Modify
your component to display the product name along with its price.
2.
Filter
products:
Add functionality to filter and display only products with a price greater than
a certain value (e.g., 500).
