Mikko Ohtamaa
Mikko Ohtamaa

Reputation: 83378

Triggering a sort on Grid.js programmatically

When I mount the GridJS component and load its data, how can I programmatically trigger the default sort on load? What methods I should call?

I am using gridjs-svelte, but that really does not matter as I can access the underlying Javascript instance.

This question is somewhat similar to the existing default sorting question.

Upvotes: 0

Views: 1232

Answers (1)

Corrl
Corrl

Reputation: 7699

In case there is no method, a workaround might be to simply trigger a click on the desired column

const column = document.querySelector('[data-column-id="email"]')
column.click()

Without gridjs-svelte REPL

<script>
    import { Grid } from "gridjs";
    import {onMount} from 'svelte'

    onMount(() => {
        new Grid({
            columns: ["Name", "Email", "Phone Number"],
            sort: true,
            data: [
                ["John", "[email protected]", "(353) 01 222 3333"],
                ["Mark", "[email protected]", "(01) 22 888 4444"],
                ["Eoin", "[email protected]", "0097 22 654 00033"],
                ["Sarah", "[email protected]", "+322 876 1233"],
                ["Afshin", "[email protected]", "(353) 22 87 8356"]
            ]
        }).render(document.getElementById("wrapper"));

        const column = document.querySelector('[data-column-id="email"]')
        column.click()
    })

</script>

<div id="wrapper"></div>

<style global>
    @import "https://cdn.jsdelivr.net/npm/gridjs/dist/theme/mermaid.min.css";
</style>

With gridjs-svelte REPL (not sure why it's only working with await tick())

<script>
    import Grid from "gridjs-svelte"
    import {onMount, tick} from 'svelte'

    const columns = ["Name", "Email", "Phone Number"]
    const data = [
        ["John", "[email protected]", "(353) 01 222 3333"],
        ["Mark", "[email protected]", "(01) 22 888 4444"],
        ["Eoin", "[email protected]", "0097 22 654 00033"],
        ["Sarah", "[email protected]", "+322 876 1233"],
        ["Afshin", "[email protected]", "(353) 22 87 8356"]
    ]

    onMount(async () => {
        await tick()
        const column = document.querySelector('[data-column-id="email"]')
        column.click()      
    })

</script>

<Grid {data} {columns} sort />

<style global>
    @import "https://cdn.jsdelivr.net/npm/gridjs/dist/theme/mermaid.min.css";
</style>

Upvotes: 1

Related Questions