Home > front end >  Fetching MongoDB data in Boostrap cards
Fetching MongoDB data in Boostrap cards

Time:04-14

I'm fetching some data from MongoDB and trying to display it in Bootstrap 5 cards. While my code works fine and data is properly fetched into Bootstrap cards, if I have 10 entries in the database, 10 cards show up in the same row.

Instead, what I want to do is use the Bootstrap grid and show a maximum of three cards per row. How can I achieve that here?

Here's the page that shows the cards:

import axios from "axios"

import Navbar from "../../components/Navbar"
import ProductCard from "../../components/ProductCard"

export default function starters({ productList }) {
    return (
        <div className="container-fluid p-0">
            <Navbar></Navbar>
            <div className="container text-center">
                <h1 className="display-3">Starters</h1>
                <div className="container text-center">
                    <div className="row">
                        <div className="col-md-4">
                            {productList.map((Product) => (
                                <ProductCard key={Product._id} Product={Product}></ProductCard>
                            ))
                            }
                        </div>
                    </div>

                </div>
            </div>
        </div>
    )
}

export const getServerSideProps = async () => {
    const res = await axios.get("http://localhost:3000/api/products")
    return {
        props: {
            productList: res.data,
        },
    }
}

And here is the card component:

export default function Products({Product}) {
    return (
        <>
            <div className="card m-5" style={{width: "18rem;"}}>
                <img src={Product.img} className="card-img-top" alt="..."/>
                    <div className="card-body">
                        <h5 className="card-title">{Product.title}</h5>
                        <p className="card-text">{Product.desc}</p>
                        <p className="card-text">{Product.prices[0]}</p>
                        <a href="#" className="btn btn-primary">Go somewhere</a>
                    </div>
            </div>
        </>
    )
}

CodePudding user response:

I think you have to move this <div className="col-md-4"> to Products.

export default function Products({Product}) {
    return (
        <div className="col-md-4">
            <div className="card m-5" style={{width: "18rem;"}}>
                <img src={Product.img} className="card-img-top" alt="..."/>
                    <div className="card-body">
                        <h5 className="card-title">{Product.title}</h5>
                        <p className="card-text">{Product.desc}</p>
                        <p className="card-text">{Product.prices[0]}</p>
                        <a href="#" className="btn btn-primary">Go somewhere</a>
                    </div>
            </div>
        </div>
    )
}
  • Related