- I want to pass posts that match certain id.
- How can I return certain components that satisfy my condition. The condition will return Post component if
post._id === user.id
post?.filter((post, id) => {
return <Post key={id} data={post} id={id}
location='profilepage' handleDelete={handleDelete} />
})
CodePudding user response:
const filteredPost = posts.filter((post) => post.id === user.id));
Now using the filteredPost you can map the component
CodePudding user response:
The filter
method doesn't change the elements inside an array, it just returns the same array with or without certain elements based on condition. What you want instead is to map
your post
variable and return a post for each post
data.
That's the explanation:
// I renamed post in posts just to clarify the code
posts?.map((post, id) =>
post._id === user.id
? <Post key={id} data={post} id={id} location="profilepage" handleDelete={handleDelete} />
: null // If you return null React won't show it
)
Anyway, the id
param isn't the id, it's just the index of the element inside the array (eg: 0, 1, 2, etc...)
CodePudding user response:
Filter method will only give you filtered but to render it you need a render method its should be done by a function..
const getPost = ()=>(
post?.map((post, id) => {
post.id === user.id && return <Post key={id} data={post} id={id} location='profilepage' handleDelete={handleDelete} />
})).filter(boolean)
In render method call finction
return (
{getPost()}
)
CodePudding user response:
This is a good use case for filter
and includes
:
const posts = [
{id: 1, name: "first"},
{id: 2, name: "second"},
{id: 3, name: "third post"}
]
const wantedPostIds = [1, 3]
console.log(posts.filter(post => wantedPostIds.includes(post.id)))