Taras Yaremkiv Taras Yaremkiv - 5 months ago 36
Javascript Question

Nice way in React to Map an array data to Card Decks

I have an array of objects. And I can't figure out how do I create multiple card decks with 3 cards in each one, as on the image:

enter image description here

An example is below:

import { Card, Button, ... CardBlock } from 'reactstrap';

export default const Example = (props) => {
return (<div>
<CardDeck>
<Card>
<CardImg top width="100%" src="https://..." />
<CardBlock>
<CardTitle>{data.title}</CardTitle>
<CardSubtitle>{data.subtitle}/CardSubtitle>
<CardText>{data.text}</CardText>
<Button>Button</Button>
</CardBlock>
</Card>
<Card>
...
</Card>
<Card>
...
</Card>
</CardDeck>

<CardDeck>
...
</CardDeck>
...
</div>
);
};

Answer Source

If your question is about how to iterate over your array then you can use Array.prototype.map() for it.

An example from the react docs with map() call using an arrow function:

By saving the components in a temporary variable:

function NumberList(props) {
  const numbers = props.numbers;
  const listItems = numbers.map((number) =>
    <ListItem key={number.toString()}
              value={number} />
  );
  return (
    <ul>
      {listItems}
    </ul>
  );
}

By using map() inline:

function NumberList(props) {
  const numbers = props.numbers;
  return (
    <ul>
      {numbers.map((number) =>
        <ListItem key={number.toString()}
                  value={number} />
      )}
    </ul>
  );
}

EDIT:

Do not render multiple <CardDeck> components. Instead adapt your css so that a <Card> will wrap into the next row when there are more that three. Then you only have to map the data inside your array once and not for every <CardDeck> again.