Applying map() Function in React.js (Arrays & Objects)
Applying map() Function
in React.js (Arrays & Objects)
1. Using map() on
Arrays in React
The map() function is used to iterate over an array and
transform its elements into JSX elements.
Example: Rendering a List from an Array
Key Points
- map() loops over the students array and returns a list of
<li> elements.
- The key prop (unique identifier) must
be added for better performance.
2. Using map() on an
Array of Objects
When dealing
with an array of objects, you can extract and render specific properties.
Example: Displaying an Array of Objects
Key Points
- students.map() iterates over the array of
objects.
- Each student’s name and
course are displayed.
- The key should be a unique
identifier (e.g., id) to improve React’s
rendering performance.
3. Using map() on an
Object (Converting Object to Array)
Since map() is available only for arrays, you must convert an
object into an array using Object.keys(), Object.values(), or Object.entries().
Example: Mapping Over an Object
Key Points
- Object.entries(student) converts the object into an
array of [key,
value]
pairs.
- map() is applied to iterate over
the key-value pairs.
Summary Table
|
Use Case |
Method |
|
Array
of values |
array.map((item, index) =>
<JSX />) |
|
Array
of objects |
array.map((obj) => <JSX
key={obj.id} />) |
|
Object
(key-value pairs) |
Object.entries(object).map(([key,
value]) => <JSX />) |
Conclusion
- map() is ideal for rendering
lists dynamically.
- Always provide a unique key when mapping over an array.
- Convert objects to arrays
before using map().
Comments
Post a Comment