-2

This gives Error at for loop

let contact=[{name:"Mithun"},{name:"Keerthana"},{name:"Jayendara"},{name:"Shivani"}]

for (i=0;i<list;i++)

{
 <h1>{content[0].name}</h1>
}
  • 1) http://stackoverflow.com/questions/29149169/how-to-loop-and-render-elements-in-react-js-without-an-array-of-objects-to-map 2) http://stackoverflow.com/questions/29859380/for-loop-in-react-render-method 3) http://stackoverflow.com/questions/22876978/loop-inside-react-jsx – Ashokkumar M. Prajapati May 11 '17 at 05:05

2 Answers2

1

You need to use contact.length rather than list in the for loop. You also need to use contact[i] rather than content[0].

for (i = 0; i < contact.length; i++) {
    <h1>{contact[i].name}</h1>
}

If you are using TSX (TypeScript + React), you can use the map function to make this easier.

return contact.map(c => <h1>{c.name}</h1>);
Derek
  • 4,351
  • 2
  • 20
  • 33
Geoff Cox
  • 6,074
  • 2
  • 26
  • 30
1

Suggest you a few things

  1. In your question you are looping over list rather than that you should be looping over contacts

  2. As I understand you wish to craete a JSX element from the contact objects. So you need to push it into an array and then render it like

Code:

let contact=[{name:"Mithun"},{name:"Keerthana"},{name:"Jayendara"},{name:"Shivani"}]
var content = [];
for (i=0;i<contact;i++)
{
 content.push(<h1>{contact[i].name}</h1>);
}

and when you want to render this in your render function you will do something like

return (
   <div>{content}</div>
)
  1. However since you are using react you should be using map function which are more convient and easy to use

Your code will look like

 render() {
     return(
         <div>
            {contacts.map(function(item) {
                 return (<h1>{item.name}</h1>)
            })}
         </div>
     )
   }
Shubham Khatri
  • 246,420
  • 52
  • 367
  • 373