Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to generate react html in a loop [duplicate]

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?

like image 708
Christofer Johnson Avatar asked Oct 16 '25 12:10

Christofer Johnson


2 Answers

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

like image 132
Leland Barton Avatar answered Oct 18 '25 02:10

Leland Barton


Or using forEach

 handleEvents = (array) => {
 if(array.length > 0){
  let tempArray = []
  array.forEach(function(each){
    tempArray.push(<h1>hello {each.name}</h1>)
 })
  return tempArray
}
like image 36
ashwintastic Avatar answered Oct 18 '25 01:10

ashwintastic



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!