Skip to content Skip to sidebar Skip to footer

How Do I Display 3 Card Components Horizontally With React Bootstrap And Grids?

db.json { 'products': [ { 'id': 1, 'name': 'Moto G5', 'quantity': 2, 'price': 13000 }, { 'id': 2, 'name': 'Racold Geyser', '

Solution 1:

You need to split the data into rows, each one containing 3 cols, each one containing a product. You can solve this problem by using a chunk function, which takes an array and a chunk size as parameters and outputs an array containing all the chunks. There are many libraries that implement this (e.g. lodash) but for the sake of simplicity, just grab the chunk function from here.

Solution

  1. Copy or import a chunk function from a well-known library.
const chunk = (arr, chunkSize = 1, cache = []) => {
  const tmp = [...arr]
  if (chunkSize <= 0) return cache
  while (tmp.length) cache.push(tmp.splice(0, chunkSize))
  return cache
}
  1. Split your data into chunks of a fixed length.
const productsChunks = chunk(props.products, 3);
  1. Render each chunk as a row containing 3 columns, with your Product component inside.
const rows = productsChunks.map((productChunk, index) => {
    const productsCols = productChunk.map((product, index) => {
        return (
        <Colxs="4"key={product.id}><Productkey={product.id}quantity={product.quantity}price={product.price}name={product.name} /></Col>
      );
    });
    return<Rowkey={index}>{productsCols}</Row>
});

That should solve your problem, let me know what you think about my solution. I've included a JSFiddle for clarity. My JSFiddle: Link

Post a Comment for "How Do I Display 3 Card Components Horizontally With React Bootstrap And Grids?"