React js Mapping
Map data in react bootstrap card component, using Map method
To map data in a React Bootstrap card component, you can use the JavaScript map() function to dynamically render an array of data into multiple Card components. Below is an example:
import React from 'react';
import { Card, Row, Col } from 'react-bootstrap';
const data = [
{ id: 1, title: 'Card 1',
text: 'This is the first card.',
imgUrl: 'https://via.placeholder.com/150' },
{ id: 2, title: 'Card 2',
text: 'This is the second card.',
imgUrl: 'https://via.placeholder.com/150' },
{ id: 3, title: 'Card 3',
text: 'This is the third card.',
imgUrl: 'https://via.placeholder.com/150' },
];
const CardList = () => {
return (
<Row xs={1} sm={2} md={3} className="g-4">
{data.map((item) => (
<Col key={item.id}>
<Card>
<Card.Img
variant="top"
src={item.imgUrl}
alt={item.title} />
<Card.Body>
<Card.Title>{item.title}</Card.Title>
<Card.Text>{item.text}</Card.Text>
</Card.Body>
</Card>
</Col>
))}
</Row>
);
};
export default CardList;
Explanation:
Data Array:
Thedataarray contains objects with information likeid,title,text, andimgUrl.Bootstrap Grid:
RowandColcomponents from React Bootstrap are used for responsive layout.- The
xs,sm, andmdprops define the number of columns on different screen sizes.
Mapping Data:
- The
map()function iterates over thedataarray and creates aCardfor each object. - The
keyprop is added to eachColto ensure unique identification of elements.
- The
Card Components:
- Each
Carddisplays an image, title, and text dynamically based on the array data.
- Each
Styling:
Theg-4class adds spacing between the cards.
Output:
This code will render a responsive grid of cards, each populated with data from the data array. You can customize the content and styles as needed.