简体   繁体   中英

How can I render out the items in my array one at a time when returning them?

I have an array of objects.

Each object has a few strings and an array of strings.

I want to render out the array of strings part of the object with an unordered list.

Right now I'm using:

const renderOut = this.props.data.filter(obj => {
   return this.state.keyToFind.includes(obj.name);
  }).map((obj, idx) => {
   return (
     <div key={idx}>
       <h2>{obj.name}</h2>
       <ul>
          <li>{obj.arrayItems}</li>
       </ul>
      </div>
    );
 });

The problem with the code above is that it renders out obj.arrayItems all in a row. For example...

[ "cup", "ball", "toy" ]

renders out as....

cupballtoy

but I'm trying to get it to look like:

  • cup
  • ball
  • toy

Is there a way I can render out obj.arrayItems one at a time?

You can use a nested map function.

 const renderOut = this.props.data.filter(obj => {
 return this.state.keyToFind.includes(obj.name);
  }).map((obj, idx) => {
   return (
     <div key={idx}>
       <h2>{obj.name}</h2>
       <ul>
         {obj.arrayItems.map(item => <li key={item}>{item}</li>)}
       </ul>
      </div>
    );
 });

Yes, create a map function to return the strings into DOM elements inside the ul. React does require a unique key prop to help keep track of these components, but for simplicity, in this case, you can use the array index.

{ obj.arrayItems.map( (item, i) => <li key={i} >{ item }</li> ) }

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