I am creating a simple search bar element in React JSX. I’m trying to render a list of elements that include whatever is in a search query. I basically take an array of all the elements and then I use .filter() function to find everything that includes the query. After that I use .map() function to loop through the results and render
<ul>
{
this.state.searchQuery &&
this.props.searchDB.projects.filter((project)=> {
if (this.state.searchQuery === '' || this.state.searchQuery === null) {
return project;
} else if (project.projectName.toLowerCase().includes(this.state.searchQuery.toLowerCase())) {
return project;
} else {
return null
}
}).map((project, index) => {
//THIS WORKS AS EXPECTED
return(
<li key={'project_' + index}>
{index + '_' + project.projectName}
</li>
)
})
}
{
this.state.searchQuery &&
this.props.searchDB.mentions.forEach((mentionYear) => {
mentionYear.filter((mention) => {
if (this.state.searchQuery === '' || this.state.searchQuery === null) {
return mention
} else if (mention.mentionTitle.toLowerCase().includes(this.state.searchQuery.toLowerCase())) {
return mention
} else {
return null
}
}).map((mention, mentionIndex) => {
console.log(mention.mentionTitle)
//THIS LOGS DATA AS IT SHOULD BUT DOESN'T RENDER ELEMENTS
return(
<li key={'project_' + mentionIndex}>
{mentionIndex + '_' + mention.mentionTitle}
</li>
)
})
}
)
}
</ul>
The first function works fine and returns a
>Solution :
The second version never does anything with the result of .map()
. It’s invoked inside a forEach()
callback, but its result is discarded. Contrast that to the first version where the result of .map()
is part of the JSX and rendered.
Don’t use forEach()
for this. If the intent is that the .forEach()
iteration should produce a result just like in the first version, then what you want isn’t forEach()
. What you want is .map()
.
For example:
{
this.state.searchQuery &&
this.props.searchDB.mentions.map((mentionYear) => {
return mentionYear.filter((mention) => {
// etc.
}).map((mention, mentionIndex) => {
// etc.
});
})
}
Basically, repeat the same pattern/structure you already know works when iterating over a collection in JSX to produce a rendered result.