function NameList() {
const names = ['Bruce', 'Clark', 'Diana']
return (
<div>
{names.map(name => <h2>{name}</h2>)}
</div>
)
}
const robots = ['Bruce', 'Clark', 'Diana']
robots.map((robot, index) => {
return (
<h1 key={index}>{robot} </h1>
)
})
//lets say we have an array of objects called data
<div className="sample">
{data.map((item)=>{
return(
<div key={item.id} className="objectname">
<p>{item.property1}</p>
<p>{item.property2}</p>
</div>
);
});
</div>
function ShowName() {
const userNames = ["Kunal", "Braj", "Sagar", "Akshay"];
return (
<>
<div>
{
userNames.map((elem) => {
<h1>{elem}</h1>
})
}
</div>
</>
);
}
export default ShowName;
render() {
return (
// using a arrow function get the looping item and it's index (i)
this.state.data.map((item, i) => {
<li key={i}>Test</li>
})
);
}
function MapComponent(){
const [myMap, setMyMap] = useState(new Map());
const updateMap = (k,v) => {
setMyMap(new Map(myMap.set(k,v)));
}
return(
<ul>
{[...myMap.keys()].map(k => (
<li key={k}>myMap.get(k)</li>
))}
</ul>
);
}
const array={{firstName:"x", lastName:"y"},{firstName:"a", lastName:"b"}}
// Method 1: Without using "{}"
array.map((item)=>(
<ComponentName fName={item.firstName} lName={item.lastName} />
));
// Method 2: With using "{}"
array.map((item)=>{
return(<ComponentName fName={item.firstName} lName={item.lastName} />)
});
export const Articles = props => {
const [articles, setArticle] = React.useState(props.data || [])
React.useEffect(() => {
if (Array.isArray(articles) && articles.length < 1) {
setArticle([
{
title: 'how to map array in react',
content: `read this code!`,
},
])
}
}, [articles])
return (
<div>
{Array.isArray(articles) &&
articles.map((item, key) => (
<article key={key}>
<h2>{item.title}</h2>
<p>{item.content}</p>
</article>
))}
</div>
)
}