I am trying to implement usestate function from a tutorial. It says that this code will traverse the array and put the values from that array in those posts, but it shows a blank when i implement it.
It works well when I give input in this way.
<Post username="cleverqazi" caption="wow it works" imageUrl="https://images.pexels.com/photos/5624397/pexels-photo-5624397.jpeg?auto=compress&cs=tinysrgb&w=1260&h=750&dpr=1" />
But not when I try in this way.
const [posts, setposts] = useState([
{ username:"cleverqazi",
caption:"wow it works",
imageUrl:"https://images.pexels.com/photos/5624397/pexels-photo-5624397.jpeg?auto=compress&cs=tinysrgb&w=1260&h=750&dpr=1",},
{ username:"its_cleverqazi",
caption:"wow it ",
imageUrl:"https://images.pexels.com/photos/5624397/pexels-photo-5624397.jpeg?auto=compress&cs=tinysrgb&w=1260&h=750&dpr=1" }
]);
{
posts.map(post=> {
<Post username={post.username} caption={post.caption} imageUrl={post.imageUrl} />
})
}
Is there any mistake in my useState function? Please help.
I was expecting to implement useState function.
CodePudding user response:
You have to return
<Post />
And add a Key/index value when using Map Meaning:
{
posts.map((data, index) => {
return <Post key={index} username={data.username} caption={data.caption} imageUrl={data.imageUrl} />
})
}