'Populate cells with HTML in Grid.js

How can I populate cells with HTML content in Grid.js?



Solution 1:[1]

Import the html function first:

import { Grid, html } from "gridjs";

then use that in formatter function or directly in data:

const grid = new Grid({
  columns: [
      { 
        name: 'Name',
        formatter: (cell) => html(`<b>${cell}</b>`)
      },
      'Email',
      { 
        name: 'Actions',
        formatter: (_, row) => html(`<a href='mailto:${row.cells[1].data}'>Email</a>`)
      },
   ],
  data: Array(5).fill().map(x => [
    faker.name.findName(),
    faker.internet.email(),
    null
  ])
});

also check out https://gridjs.io/docs/examples/html-cells

Solution 2:[2]

I'm using gridjs CDN implementation via browser, I can use formatter by accessing the html function via gridjs namespace as per below

    {
        name: "Action",
        formatter: (cell) => {
            return gridjs.html(`<a href="">update</a>`)
            // return `Update button`
        }
    }

Solution 3:[3]

For me, I set the script type "text/javascript" to "module". And then I can use "import" like this =>

<script type="module">
        import {
            Grid,
            html
        } from "/Scripts/gridjs.production.es.min.js";
        
        //then use html with formatter

        {
           name: "Actions",
           formatter: (cell) => {
           return html(`<a data-id=${cell} href="#"><span class="glyphicon glyphicon-pencil"></span>Edit</a>`)
        }
}
</script>

Solution 4:[4]

You can also modify the data received with a service or something else and then pass it in html ;)

import { Grid, html } from "gridjs";

const columns = [
        {
            id: 'difficulty',
            name: 'Difficulté',
            formatter: (cell) => {
                const difficultyConverter = new DifficultyConverter()
                const displayedDifficultyResults = difficultyConverter.getNameAndAssociatedClassName(cell, null)

                return html(`<span class='badge ${displayedDifficultyResults.originClassToAdd}--active'>${displayedDifficultyResults.originName}</span>`)
            }
        },
        {
            id: 'community_difficulty',
            name: 'Communauté',
            formatter: (cell) => {
                const difficultyConverter = new DifficultyConverter()
                const displayedDifficultyResults = difficultyConverter.getNameAndAssociatedClassName(cell, null)

                return html(`<span class='badge ${displayedDifficultyResults.originClassToAdd}--active'>${displayedDifficultyResults.originName}</span>`)
            }
        },
]

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Afshin Mehrabani
Solution 2 mdennisa
Solution 3
Solution 4 user16087481