-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

3 Answers3

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,575
  • 3
  • 22
  • 36
Geoff Cox
  • 6,102
  • 2
  • 27
  • 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
  • 270,417
  • 55
  • 406
  • 400
0

Allow me to offer a TypeScript solution in addition to the JavaScript ones above.

const getCustomerRows = (customers: []): Array<any> => {
    const rows: Array<any> = [];

    for(let i = 0; i < customers.length; i++) {
      rows.push(<YourComponent
      name={customerName}
      age={customerAge}
      ></YourComponent>)
     }
    
     return rows;
 }


...
<header>Some Header</header>
{getViewerBkgrdRows().map((row) => row)}
<div>some div</div>
Joey Garcia
  • 315
  • 3
  • 7