DEV Community

Sonu Jangra
Sonu Jangra

Posted on

Setting Up AG Grid in SvelteJS

AG Grid is a powerful and feature-rich grid component for displaying large datasets in a flexible and efficient way. If you're using SvelteJS version 5.0.0 and want to integrate AG Grid into your project, you're in the right place! In this blog, I'll walk you through the process of setting up AG Grid in Svelte, including installing the necessary dependencies, configuring the grid, and rendering it in your Svelte components.

Prerequisites
Before we start, make sure you have the following:

  • Node.js installed (Preferably the latest stable version).
  • A Svelte project setup (If not, you can create one by running npm create svelte@latest).
  • Basic understanding of SvelteJS and its component-based structure.

Step 1: Installing Dependencies
To begin, you need to install AG Grid and its necessary styles in your Svelte project. Open your terminal and run the following commands:

npm install --save ag-grid-community

Step 2: Creating the AG Grid Component
Now that we have the necessary dependencies installed, let’s create a Svelte component to render the grid.

  • In your src/routes (or src/components/common/) folder, create a new file called Grid.svelte.
  • Add the following code to initialize and render the AG Grid:
<script lang="ts">
    import { onMount } from 'svelte';
    import {
        createGrid,
        ModuleRegistry,
        ClientSideRowModelModule,
        type GridOptions,
        themeQuartz,
        colorSchemeDarkBlue
    } from 'ag-grid-community';

    // Register AG Grid Modules
    ModuleRegistry.registerModules([ClientSideRowModelModule]);

    export let columnDefs: Array<any> = [];
    export let rowData: Array<any> = [];

    // Create a custom dark theme using Theming API
    const darkTheme = themeQuartz.withPart(colorSchemeDarkBlue).withParams({
        backgroundColor: '#212121',
        foregroundColor: '#ffffff',
        headerBackgroundColor: '#37474f',
        headerTextColor: '#cfd8dc',
        oddRowBackgroundColor: '#263238'
    });

    let gridDiv: HTMLDivElement;

    onMount(() => {
        const gridOptions: GridOptions<any> = {
            theme: darkTheme, // Apply custom dark theme
            columnDefs,
            rowData,
            defaultColDef: {
                sortable: true,
                filter: true
            }
        };

        if (gridDiv) {
            createGrid(gridDiv, gridOptions); // Create the grid with custom options
        }
    });
</script>

<!-- Grid Container -->
<div bind:this={gridDiv} style="height: 400px; width: 100%;"></div>
Enter fullscreen mode Exit fullscreen mode

Here’s a breakdown of the code:

  • columnDefs: Defines the columns you want in your grid, including the headers and the field names from the row data.
  • rowData: Holds the data that will populate the grid.

Step 3: Using the AG Grid Component
Next, let’s use the Grid.svelte component we just created in the main Svelte component (usually App.svelte).

Open src/App.svelte and add the following code:

<script>
    import Grid from '../../components/common/Grid.svelte';
    const columns = [
        { headerName: 'Course', field: 'course' },
        { headerName: 'Instructor', field: 'instructor' },
        { headerName: 'Duration', field: 'duration' },
        { headerName: 'Location', field: 'location' },
        { headerName: 'Rating', field: 'rating' }
    ];

    const rows = [
        {
            course: 'JavaScript Basics',
            instructor: 'John Doe',
            duration: '5 hours',
            location: 'Delhi',
            rating: '3'
        },
        {
            course: 'Svelte Fundamentals',
            instructor: 'Jane Smith',
            duration: '3 hours',
            location: 'Delhi',
            rating: '2'
        },
        {
            course: 'Advanced React',
            instructor: 'Jake White',
            duration: '6 hours',
            location: 'Delhi',
            rating: '5'
        }
    ];
</script>

<h1>Training Courses</h1>
<Grid columnDefs={columns} rowData={rows} />
Enter fullscreen mode Exit fullscreen mode

Step 4: Run Your Project
Now that everything is set up, it’s time to run your project. In the terminal, run the following command:

npm run dev

This will start the Svelte development server, and you should be able to navigate to your app in the browser. If everything is set up correctly, you should see the AG Grid displaying the data we defined in the Grid.svelte component.

setting-up-ag-grid-in-sveltejs

Top comments (1)

Collapse
 
webjose profile image
José Pablo Ramírez Vargas • Edited

Interesting. Allow me to point out a few things I see incorrect.

Svelte v4 Properties

The code:

    export let columnDefs: Array<any> = [];
    export let rowData: Array<any> = [];
Enter fullscreen mode Exit fullscreen mode

Is declaring properties in v4 style. It should be, for v5:

    let {
        columnDefs,
        rowData,
    }: {
        columnDefs: Array<any> = [];
        rowData: Array<any> = [];
    } = $props();
Enter fullscreen mode Exit fullscreen mode

The onMount Code Doesn't Clean Up

The call to createGrid() must be returning something that is disposable somehow, and that disposal process should be triggered by the return value of onMount.

Using any Kills TypeScript

The any type is a last-resort kind of thing. Instead, you can declare the component with generics:

<script lang="ts" generics="TCol, TRow">
    ...
    let {
        columnDefs,
        rowData,
    }: {
        columnDefs: Array<TCol> = [];
        rowData: Array<TRow> = [];
    } = $props();
    ...
</script>
Enter fullscreen mode Exit fullscreen mode