Home > Software engineering >  How do I map an array of objects with react
How do I map an array of objects with react

Time:04-01

This is the Array I'm trying to map

const arr = [
{"title" : "something",
 "Text" : "something"
},
{"title" : "something",
 "Text" : "something"
},
{"title" : "something",
 "Text" : "something"
}

]

Tried to map it like this

{arr.map((item, index) => {
    return (
      <div key={index}>
         <p>{item.title}</p>
         <p>{item.Text}</p> 
         <button>
           click here 
         </button>
      </div>
    )
})}

It won't work so what am i missing here?

edited*

CodePudding user response:

Why your Const is capital, it should be const and item.text should be item.Text

const arr = [
{"title" : "something",
 "Text" : "something"
},
{"title" : "something",
 "Text" : "something"
},
{"title" : "something",
 "Text" : "something"
}
]

{arr.map((item, index) => {
    return (
      <div key={index}>
         <p>{item.title}</p>
         <p>{item.Text}</p> 
         <button>
           click here 
         </button>
      </div>
    )
})}

CodePudding user response:

Const needs to be lowercase

const arr = [
 { 
   "title" : "something",
   "Text" : "something"
 },
 {
   "title" : "something",
   "Text" : "something"
 },
 {
   "title" : "something",
   "Text" : "something"
 }
];

The Title key in you object is catitalized

{arr.map((item, index) => {
    return (
      <div key={index}>
         <p>{item.title}</p>
         <p>{item.Text}</p> 
         <button>
           click here 
         </button>
      </div>
    )
})}

Or you also can do it like this

{arr.map(({title, Text}, index) => {
    return (
      <div key={index}>
         <p>{title}</p>
         <p>{Text}</p> 
         <button>
           click here 
         </button>
      </div>
    )
})}
  • Related