Okay so this is has been driving me mad for the past few hours. Pretty much i want to have a function that generates html based off of objects in an array that are passed to it as an argument. My Code looks something like this:
handleEvents = (array) => {
if(array.length > 0){
array.forEach(function(each){
return(<h1>hello {each.name}</h1>)
})
}
And in my render component i have this:
<div className="caption left-align">
<h3>Upcoming events</h3>
{this.handleEvents([{name: "Dave"}, {name: "Mary"}, {name: "Chris"}])}
</div>
But when i run this code nothing is being output to the screen. What should i do?
The only problem is that Arrays.forEach
does not return anything. If you change your handleEvents function to look more like
if(array.length > 0){
return array.map(function(each){
return(<h1>hello {each.name}</h1>)
})
} else {
return []
}
This should return an h1. The map function will return a list of the elements returned
Or using forEach
handleEvents = (array) => {
if(array.length > 0){
let tempArray = []
array.forEach(function(each){
tempArray.push(<h1>hello {each.name}</h1>)
})
return tempArray
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With