简体   繁体   中英

Rendering React Components from Array of Objects in state

I have a object like this in my this.state.data :

{
  "companies": [
    {
      "id": 1,
      "description": "Fernando"
    },
    {
      "id": 2,
      "description": "Paulo"
    }
  ]
}

I get this object from a get method in a url and set him in my this.state.data . I want to render my menu with options that are the descriptions of the array, like this :

 <MenuItem value={10} >Fernando</MenuItem>
 <MenuItem value={20}>Paulo</MenuItem>

But i want to make it render dynamiclly, sometimes i will recieve a array with 10 id's and descriptions, so i need to render 10 options in the menu. I already try to map the object, but i'm still stuck at this.

PS: I'm setting the content on a state because i can change it anytime.

Are you just wanting the description to be dynamically added?

You can do

this.state.data.companies.map(company => (
   <MenuItem key={company.id}>{company.description}</MenuItem>
))

This will return a MenuItem for each item in the array

I'm not sure what you need for the value prop but that can be dynamically changed in the same manner

Inside the render method,

{this.state.data.companies.map((company) => {
   <MenuItem id={company.id} key={company.id} description={company.description}/>
})}

Then use the company description inside the MenuItem component as this.props.description

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM