简体   繁体   中英

How to take certain number of elements from Array in React

Ok so I have a frontend that displays cards. The information comes from my GraphQL api.It makes the request and sends the props to a card component. I have different size cards. I want the first 3 elements from the array to go to the small cards and then the rest to go to the big cards. How can I do this?

The react code I have right now is:

           {loading ? (
              <h1>Loading Campaigns...</h1>
            ) : (
              data && data.campaigns.map(campaign => (
                <Grid item xs={12} sm={6} md={4} key={campaign.id}>
              <Card campaign={campaign} cbody = {campaign.body} title = {campaign.title}
              
              />
              </Grid>
              ) )
            )}

Campaign is basically each element in the array.

Use slice like:

data.campaigns.slice(0,3).map(...)

So you will end up with two maps for that case, but that's fine.

Or you could use the index of the current map and check if the index is less than 3, and do conditional rendering there directly

Using index inside map

data && data.campaigns.map((campaign, index) => {return /*condtional rendering here*/} )

using slice

First three

data && data.campaigns.slice(0,3).map( item => /*render here*/)

rest

data && data.campaigns.slice(3).map( item => /*render here*/)

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