i am newbie in javascript and react. I need a way to automatically arrange the cards in new rows. Something like three cards per row, and if I have more than three, create a new row for the 4th card. and i find an answer but i couldn't convert that way to my project. I am self-taught and it is my first project practice.
My code:
{
this.props.products.map((product) => (
<Row>
<CardGroup>
<Card>
<CardImg
top
width="100%"
src={`${process.env.PUBLIC_URL}/assets/images/1.jpg`}
alt="Card image cap"
/>
<CardBody>
<CardTitle tag="h5">{product.productName}</CardTitle>
<CardSubtitle tag="h6" className="mb-4 text-muted">
author
</CardSubtitle>
<CardText>casdadasdx</CardText>
</CardBody>
</Card>
</CardGroup>
</Row>
));
}
Answer: You could create an array with groups of 3 cards and then iterate over them: Answer code:
const arr = var x = arr.reduce((item, key, index) => (index % 3 == 0 ? item.push([key]) : item[item.length-1].push(key)) && item, []);
const Items = ({items}) => (
<>
<container>
{arr.map(group => (
<row>
<CardGroup>
{group.map(card => (
<Card style={{ width: '18rem' }}>
<Card.Body>
<Card.Title>{item.NOME}</Card.Title>
<Card.Subtitle className="mb-2 text-muted">{item.CATEGORIA}</Card.Subtitle>
<Card.Text>{item.DESCRICAO}</Card.Text>
<Card.Link href="#">Card Link</Card.Link>
<Card.Link href="#">Another Link</Card.Link>
</Card.Body>
</Card>
))}
</CardGroup>
</row>
))}
</container>
</>
);
Is this what you need?
import "./styles.css";
import { Row, Col, Card, CardHeader, CardBody } from "reactstrap";
export default function App() {
return (
<div className="App">
<Row>
{Array.from(Array(7)).map((item, index) => {
return (
<Col md={4} lg={4} sm={4} xs={12} key={index}>
<Card>
<CardHeader>Header {index + 1}</CardHeader>
<CardBody>Body {index + 1}</CardBody>
</Card>
</Col>
);
})}
</Row>
</div>
);
}
Here is the full working sample https://codesandbox.io/s/romantic-thunder-drchc?file=/src/App.tsx