I am building a simple blog app and I am trying to check if blog is in liked blogs array in return function. So I have created two array, one of all blogs and another of liked blogs and I am trying to show message that "Blog is liked" But two map functions in return statement is showing unexpected results or showing strange multiple results.
App.js
class Blogs extends React.Component {
const all_blogs = [
{"blog_title" : "First Blog"},
{"blog_title" : "Second Blog"},
{"blog_title" : "Third Blog"},
{"blog_title" : "Fourth Blog"},
{"blog_title" : "Fifth Blog"},
]
const liked_blogs = [
{"blog_title" : "Second Blog"},
{"blog_title" : "Third Blog"},
]
render() {
return (
<div>
{
all_blogs.map(blog =>
liked_blogs.map(liked_blog => {
if (blog.blog_title === liked_blog.blog_title) {
return (
<div>This blog is liked</div>
)
} else {
<div>This blog is NOT liked</div>
}
}
}
</div>
)
}
}
I am trying to check if all_blogs blog is in liked_blogs liked or not in liked, and If blog is liked then show return div then if not then show else div
I have tried many times but it is still not working.
>Solution :
The nested map will return multidimention array which will not output the expected result, you need the some method to find if the blog exists in the linked_blogs or not, then conditionally show the message.
class Blogs extends React.Component {
const all_blogs = [
{"blog_title" : "First Blog"},
{"blog_title" : "Second Blog"},
{"blog_title" : "Third Blog"},
{"blog_title" : "Fourth Blog"},
{"blog_title" : "Fifth Blog"},
]
const liked_blogs = [
{"blog_title" : "Second Blog"},
{"blog_title" : "Third Blog"},
]
render() {
return (
<div>
{
all_blogs.map(blog =>
liked_blogs.some(liked_blog => blog.blog_title === liked_blog.blog_title) ? <div>This blog is liked</div> : <div>This blog is NOT liked</div>)
}
</div>
)
}
}