What is list Rendering?
List are very useful when it comes to developing the UI of any website.
List are mainly used for displaying list of things in a website.
Ex- list of products, list of names, list of courses etc.
In react ,you will render lists with some type of loop.
The javascript
map()
array method is generally the preferred method.
list render a array
import React from 'react'
function User() {
const student =["ANKU","MANKU","ANKI","MANKI"];
return (
<div>
{student.map(std => <h1>{std}</h1> )}
</div>
)
}
list render a object
function User() {
const student =[
{
name:"manki",
age:23
},
{
name:"anki",
age:23
},
{
name:"anku",
age:22
}
]
return (
<div>
{student.map(std => <h1>i am {std.name} and age is {std.age}</h1>)}
</div>
)
}
call component in map method
function User() {
const student =[
{
name:"manki",
age:23
},
{
name:"anki",
age:23
},
{
name:"anku",
age:22
}
]
return (
<div>
{student.map(std => <App stds={std}/> ) }
</div>
)
}
function App({stds}) {
return (
<div>
<h1>i am {stds.name} and age is {stds.age}</h1>)}
</div>
)
}
map()
create a new array from calling a function for every array elements.map()
calls a function once for each element in an erray.map()
does not execute the function for empty elements.map()
does not change the original array.
List and Keys
Keys allow react to keep track pf elements.
This way, if an intern is updated or removed, only that item will be re-rendered instead of the entire list.
Keys need to be unique to each sibling.
Generally the key should be a unique id assigned to each items. As a last resort, you can use the array index as a key.
A key is a special string attribute you need to include whe creating list of elements in react.
keys are used to react to identify which items in the list are changed, updated or deleted.
function User() {
const student = ["anki","anku","manki","manku"];
let studentname = student.map((std, index) => <li key={index}>{std}</li>);
return (
<div>
{<ul> {studentname} </ul>}
</div>
)
}
list without keys in react
warning:- Each child in an array or iterator should have a unique "key" prop.
HAPPY LEARNING..