Ways to efficiently display elements in a grid in real-time

Attempting to design a layout where each row consists of 3 cards using Bootstrap's Grid layout for responsiveness.

The challenge lies in the fact that the card data is stored in JSON format, and the length of the JSON Object array may vary, leading to a different number of cards to display.

The goal is to dynamically render the cards using VueJS, bootstrap-vue, and JSON.

It has been understood that the number of objects in the JSON corresponds to the number of cards on the screen, with

number of cards / 3 = number of rows
.

Currently utilizing Vue-js and bootstrap-vue to accomplish the task but facing obstacles in rendering the cards dynamically within the grid.

Check out the code snippet below from CardRenderer.vue:

<template lang="html">

  <div>
    <hr>   
    <b-container class="bv-example-row">
  <b-row v-for="row in rows" :key="row.id">
    <b-col v-for="card in row.cards" :key="card.id">
      <b-card
        :title="card.title"
        img-src="https://picsum.photos/600/300/?image=25"
        img-alt="Image"
        img-top
        tag="article"
        style="max-width: 20rem;"
        class="mb-2"
      >
      <b-card-text>
        Some quick example text to build on the card title and make up the bulk of the card's content.
      </b-card-text>

      <b-button href="#" variant="primary">Go somewhere</b-button>
      </b-card>
    </b-col>
  </b-row>
</b-container>

  </div>

</template>

<script lang="js">
  export default {
    name: 'CardRenderer',
    props: {
      passer: Object
    },
    mounted() {
      // eslint-disable-next-line
      console.log(this.renderObject);
    },
    computed: {
      rows() {
        let totalRows = Math.ceil(this.passer.length / 3);
        let counter = 0;
        return Array.from({ length: totalRows }, () => ({
          id: ++counter,
          cards: this.passer.slice((counter - 1) * 3, counter * 3),
        }));
      }
    }
  }
</script>

<style scoped>

</style>

This represents a static structure of the page. All rendered cards should correspond to the JSON data passed, which is stored within the JSON.

Need guidance on dynamically rendering cards in a grid layout.

Answer №1

If you're looking to simplify the process, consider utilizing a computed property to automatically sort the array.

<script lang="js">
    export default {
        name: 'CardRenderer',
        props: {
            passer: Object
        },
        mounted() {
            // eslint-disable-next-line
            console.log(this.renderObject);
        },
        data() {
            return {

            }
        },
        methods: {

        },
        computed: {
            rows() {
                var rows = []
                var itemsPerRow = 3
                // assuming passer is an array of items..
                var arr = this.passer
                for (var i = 0; i<arr.length; i+=itemsPerRow){
                    var row = []
                    for (var z = 0; z<itemsPerRow; z++) {
                        row.push(arr[i + z])
                    }
                    rows.push(row)
                }
                return rows
            }
        }
    }
</script>

Once set up, you can easily loop through the rows in your template with the following structure:

<template lang="html">
    <div>
        <hr>
        <b-container class="bv-example-row">
            <b-row v-for="row in rows">
                <b-col v-for="item in row">
                    <!-- your card content here -->
                    <b-card title="renderObject.title" img-src="https://picsum.photos/600/300/?image=25" img-alt="Image" img-top tag="article" style="max-width: 20rem;" class="mb-2">
                        <b-card-text>
                            <h1>item data:</h1>
                            <pre>{{item}}</pre>
                        </b-card-text>
                        <b-button href="#" variant="primary">Go somewhere</b-button>
                    </b-card>
                </b-col>
                </b-col>
            </b-row>
        </b-container>
    </div>
</template>

Remember to include a unique key when using v-for in order to maintain state. If your data lacks a suitable attribute, utilize the array index as the key. Learn more at https://v2.vuejs.org/v2/guide/list.html#Maintaining-State

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Guide on implementing a redirect to a different page following form submission with the inclusion of a loading screen

<form action='page.html' method='post'> <input type="text" name="name" placeholder="Enter your name here"> <input type="submit" value="submit"> </form> The cod ...

"Typescript throws a mysterious 'Undefined value' error post-assignment

I'm currently working on a task to fetch my customer's branding information based on their Id using Angular. First, I retrieve all the customer data: this.subscription = this.burstService.getBurst().subscribe(async(response) => { if (r ...

Is it possible to use the `fill` method to assign a value of type 'number' to a variable of type 'never'?

interface Itype { type: number; name?: string; } function makeEqualArrays(arr1: Itype[], arr2: Itype[]): void { arr2 = arr2.concat([].fill({ type: 2 }, len1 - len2)); } What is the reason for not being able to fill an array with an ob ...

Overflow of dropdown menus in HTML CSS

Hello, I am new to both html and stack overflow. Please forgive me if this question has already been asked, as I couldn't find anything (but maybe I didn't search enough?). I have tried using overflow and clear properties, but I am struggling to ...

What could be causing the error 404 message to appear when trying to retrieve video data?

I'm having trouble displaying a video in mp4 format from the code's folder. When I attempt to fetch the video by clicking on the button, it shows an empty space instead of displaying the video. Here is an example of what the output looks like. T ...

Steps for transferring a value to a different page after it has been selected from a listview

web page layout <!DOCTYPE html> <html lang="en"> <head> <title>Student Information</title> <meta charset="utf-8"> <meta name="viewport" content="width=device-width, initial-scale=1"> <link rel="styleshe ...

Cloned element does not trigger on click event

When using jQuery 1.10, I encountered an issue where cloning a div containing a button with a click event defined did not retain the click event on the cloned div. I have come across similar questions multiple times, and existing solutions advise using cl ...

Issue arises when component is mistakenly displayed in the header upon deployment on Vercel platform

When deploying my NextJS app to Vercel, I encounter an issue where state-based modals that should be hidden are displaying. Additionally, the modals are rendering in the header instead of center-screen as expected. Surprisingly, these problems do not occur ...

What is the best way to compare two arrays in my JSON data?

Hello, I'm trying to compare two arrays - one from my JSON data and the second from a regular array. Specifically, I want to check if the ids of "cm:taggable" exist in my secondArray. JSON { "entry": { "isFile": true, "createdByUs ...

Is it appropriate to use localStorage in the createSlice "reducers" parameter of React Redux Toolkit?

I'm working on implementing a basic favorites list feature. Currently, there is no backend functionality in place so this will be stored in the localStorage. It might potentially switch to an API call in the future. Would it be considered acceptable ...

Incorporate a vibrant red circle within a tab of the navigation bar

I'm looking to incorporate a red dot with a number into a messaging tab to indicate new messages. Below is the HTML code: <ul class="nav pw-nav pw-nav--horizontal"> <li class="nav-item"> <a class="nav ...

Choose only one option from the dropdown menu at a time within the specified div

I attempted to utilize the "setSelected" option on my multiselect feature, but I noticed that it does not function with div elements (at least I could not make it work myself). I am endeavoring to create two synchronized multiselects using this example: b ...

What is the best method to access an element with Vue.js?

I currently have a form set up like this <form v-on:submit.prevent="save_data(this)"></form> and a method defined in Vue.js like this methods: { save_data: function(f){ } } In jQuery, we can access the form using $(f)[0] My question ...

Utilizing JavaScript to iterate through objects retrieved via Ajax calls

Recently, I've been diving into the world of Javascript and delving deep into AJAX. Utilizing Vanilla JS along with simple AJAX, my current task involves fetching a user object from a URL based on the user's input ID. Despite attempting to use .d ...

Tips on incorporating toggle css classes on an element with a click event?

When working with Angular typescript instead of $scope, I am having trouble finding examples that don't involve $scope or JQuery. My goal is to create a clickable ellipsis that, when clicked, removes the overflow and text-overflow properties of a spec ...

What is the best way to enclose a block of content with <div> and </div> tags using the append() function?

My goal is to add an outer div container by first appending it, then adding content, and finally appending the closing tag. However, I'm encountering an issue where the div I added at the beginning automatically closes itself, resulting in two separat ...

Create a new attribute within the ng-model object once it has been updated through ng-repeat

I am trying to figure out how to add a "discountRate" property to an ng-model object after it has been changed within an ng-repeat block. Check out this example for more information Another example can be found here Although the ng-model is updated as e ...

I built a custom Angular application integrated with Firebase, and I'm looking for a way to allow every user to have their individual table for managing tasks

I am looking to enhance my code so that each user who is logged in has their own tasks table, which they can update and delete. Additionally, I need guidance on how to hide menu items tasks, add-tasks, logout for users who are not logged in, and display th ...

Attempting to abbreviate repetitive Javascript instructions

I have this functional javascript code, but I feel like there might be a more efficient way to write it. Any suggestions on simplifying this? let searchTerm = 'Some search text'; const isMatch = entry.title.toLowerCase().includes(searchTer ...

`Why is the color of the <select> element not changing in Firefox?`

I seem to be facing some difficulty replicating this issue accurately. However, I do have a jsfiddle link where the selected text color does not match the selected option text. http://jsfiddle.net/kralco626/9xJvF/8/ (similar to: seting <select> col ...