-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

3 Answers 3

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>);
Sign up to request clarification or add additional context in comments.

Comments

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>
     )
   }

Comments

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>

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.