Getting Started with SVAR DataGrid in Svelte: The Guide You Actually Need – Hyperboard
Safari issues on MacBook: best ways to fix slow loading and errors. Safari issues
Slow Mac problems: best ways to fix freezing and poor performance. best ways to fix freezing and poor performance
Offre spéciale🎁🌞 L’hyperboard Pro One à 1650€ au lieu de 1950€ toute l’année !
🎁 Bonus exclusifs : Balance connectée à 89€ + Hypergun à 249€ offerts ! 💥
💪 Sculptez votre corps en seulement 10 min/jour 💪
Non classifié(e)

Getting Started with SVAR DataGrid in Svelte: The Guide You Actually Need






SVAR DataGrid for Svelte: Complete Beginner’s Setup Guide






Getting Started with SVAR DataGrid in Svelte: The Guide You Actually Need

Data tables · Installation · Column config · Sorting & Filtering · Real examples

If you have ever tried to add a serious Svelte data table component to a production app, you already know the landscape: either the library is too lightweight to be useful, or it comes with so many dependencies that it might as well be a second frontend framework. SVAR DataGrid sits in the sweet spot — a fully-featured, reactive Svelte grid component that does not try to rewrite your entire project around itself.

This guide covers everything from first install to real configuration: columns, sorting, filtering, and the handful of things the official docs mention only in passing. Whether you are migrating from the older wx-svelte-grid package or starting fresh, this is the practical walkthrough that the getting-started page should have been.

We will keep the theory short and the code plentiful. By the end, you will have a working, sortable, filterable data grid running in your Svelte project — without having spent three hours chasing TypeScript errors.

What Is SVAR DataGrid and Why Does It Exist?

SVAR DataGrid — published as the svar-datagrid npm package — is an interactive data grid built specifically for Svelte. It is maintained by the SVAR UI team, the same group behind a broader ecosystem of Svelte UI components. The library replaced the older wx-svelte-grid package around 2023, inheriting its feature set while adopting a cleaner API and proper Svelte 5 rune support.

The core premise is simple: you hand the component a flat array of data objects and a column definition array, and it gives you back a scrollable, sortable, filterable, and optionally editable table — all reactive, all in Svelte idioms. No jQuery, no custom virtual DOM, no hidden magic. Column resizing, row selection, frozen columns, and virtual scrolling for large datasets are first-class features, not afterthoughts bolted on via plugins.

Compared to generic Svelte table component libraries like svelte-table or tanstack-table’s Svelte adapter, SVAR DataGrid skews toward batteries-included. You trade a small amount of configurative freedom for a significant amount of implementation time. For enterprise dashboards, admin panels, and analytics UIs, that trade is almost always worth it.

Installation: From Zero to Running Grid

The svar-datagrid installation process is intentionally painless. Start with a standard Svelte or SvelteKit project — the component works in both, with or without SSR, though you will want to load it client-side if you are doing server-side rendering.

# Install the package
npm install svar-datagrid

# Or with pnpm
pnpm add svar-datagrid

# Or with yarn
yarn add svar-datagrid

Once installed, import both the component and its required stylesheet. The stylesheet is not optional — skipping it produces a grid that technically works but looks like a 2003 HTML table with an identity crisis.

<script>
  import { DataGrid } from "svar-datagrid";
  import "svar-datagrid/dist/svar-datagrid.css";
</script>

That is genuinely the entire installation. No peer dependencies to resolve, no Vite plugin to configure, no PostCSS pipeline to patch. If you are upgrading from the legacy wx-svelte-grid package, uninstall it first (npm uninstall wx-svelte-grid), swap the import paths, and adjust any column props that changed in the new API — mostly flexgrow is now flex, and editor definitions are slightly restructured. The migration takes under an hour for most mid-sized projects.

Your First Data Grid: Minimal Working Example

Before diving into configuration depth, here is the absolute minimum to get a Svelte DataGrid on screen. Two arrays — data and columns — and one component. Everything else is optional.

<script>
  import { DataGrid } from "svar-datagrid";
  import "svar-datagrid/dist/svar-datagrid.css";

  // Your dataset — any array of objects works
  let data = [
    { id: 1, name: "Alice Hartman", role: "Engineer", salary: 95000 },
    { id: 2, name: "Bob Kimura",    role: "Designer",  salary: 82000 },
    { id: 3, name: "Carol Mendes",  role: "Manager",   salary: 110000 },
    { id: 4, name: "David Osei",    role: "Engineer",  salary: 97000 },
    { id: 5, name: "Eva Larsson",   role: "Analyst",   salary: 78000 },
  ];

  // Column definitions
  let columns = [
    { id: "id",     header: "ID",       width: 60  },
    { id: "name",   header: "Name",     flex: 1    },
    { id: "role",   header: "Role",     width: 120 },
    { id: "salary", header: "Salary",   width: 120 },
  ];
</script>

<div style="height: 400px;">
  <DataGrid {data} {columns} />
</div>

One thing that catches beginners every time: the parent container must have an explicit height. The grid expands to fill its container, so if the container has no height, you get a zero-pixel grid that is technically rendered but completely invisible. Set height: 400px or use a flex/grid layout parent — either works. The component does not hardcode any internal dimensions, which is actually the correct behavior for a production component.

The flex: 1 property on the Name column tells the grid to expand that column to fill available horizontal space, similar to CSS flex-grow. Columns without flex get a fixed width in pixels. You can mix both freely, and the grid handles the math. If you have ever hand-implemented responsive column widths in a plain HTML table, you will appreciate this immediately.

Column Configuration: Where Real Power Lives

The column definition object is the control panel of svar-datagrid. Most of the component’s capabilities are unlocked by adding properties to these objects rather than by passing global component props. This design keeps the template clean and makes column-specific behavior explicit and co-located with the column it affects.

let columns = [
  {
    id: "name",
    header: "Full Name",
    flex: 1,
    sort: true,           // Enable column sorting
    resize: true,         // Allow user to resize this column
    filter: true,         // Enable text filter for this column
    minWidth: 150,        // Minimum width when resizing
  },
  {
    id: "salary",
    header: "Salary (USD)",
    width: 140,
    sort: true,
    template: (value) => `$${value.toLocaleString()}`,  // Custom cell renderer
  },
  {
    id: "status",
    header: "Status",
    width: 110,
    options: [            // Dropdown filter options
      { id: "active",   label: "Active"   },
      { id: "inactive", label: "Inactive" },
    ],
    filter: "select",     // Use select-type filter
  },
];

The template property is particularly useful for formatting — it accepts a function that receives the raw cell value and returns a formatted string. Need to display currency, dates, percentages, or truncated text? One line per column, no custom cell component required. For more complex rendering that involves Svelte components or HTML elements, the library also supports a cell slot, though the template function covers 80% of real-world cases.

Frozen columns — those that stay fixed while the rest scroll horizontally — are configured with frozen: true. Frozen columns must be declared first in the columns array and cannot currently be placed at the right edge (left-frozen only). For most data-dense admin interfaces, freezing the identifier and name columns is standard practice, and it works exactly as you would expect: the non-frozen columns scroll under the frozen ones with no visual glitches.

Sorting and Filtering: Making Tables Actually Useful

A data table without sorting and filtering is just a fancy list. SVAR DataGrid treats both as first-class column-level features, which means you can have some columns sortable and others not, some filtered and others left clean — all declared directly in your column config rather than through a separate plugin or wrapper component.

Sorting activates with a single property on any column: sort: true. Once enabled, clicking the column header cycles through ascending, descending, and unsorted states. The default sort is lexicographic for strings and numeric for numbers, which covers most cases correctly out of the box. If you need custom sort logic — say, sorting by a derived value or a locale-aware string comparison — you can pass a sort comparator function instead of true.

// Custom sort comparator example
{
  id: "lastName",
  header: "Last Name",
  sort: (a, b) => a.lastName.localeCompare(b.lastName, "en", { sensitivity: "base" }),
}

Filtering in svar-datagrid appears as an input row directly below the header. Text columns get a text input with a configurable match mode (contains, starts with, equals). Select/enum columns get a dropdown. Number columns support range inputs. All filters are applied client-side by default, which is instantaneous for datasets under ~50,000 rows. For server-side filtering — necessary for truly large datasets — the component exposes filter change events that you can wire to your API calls.

<script>
  import { DataGrid } from "svar-datagrid";
  import "svar-datagrid/dist/svar-datagrid.css";

  let data = [...]; // your data array

  let columns = [
    {
      id: "name",
      header: "Name",
      flex: 1,
      sort: true,
      filter: true,       // text filter, default "contains" mode
    },
    {
      id: "department",
      header: "Department",
      width: 160,
      filter: "select",   // dropdown filter
      options: [
        { id: "engineering", label: "Engineering" },
        { id: "design",      label: "Design"      },
        { id: "marketing",   label: "Marketing"   },
      ],
    },
    {
      id: "salary",
      header: "Salary",
      width: 130,
      sort: true,
      filter: "number",   // numeric range filter
    },
  ];
</script>

<div style="height: 500px">
  <DataGrid {data} {columns} />
</div>
Pro tip: If you enable filtering, also set headerRowHeight on the DataGrid component to give the filter row comfortable spacing. The default is functional but tight on mobile viewports.

Pagination, Virtual Scrolling, and Large Datasets

Handling thousands of rows in a browser is where most lightweight Svelte table libraries quietly give up. SVAR DataGrid offers two strategies depending on your UX preference: traditional pagination and virtual scrolling. They are not mutually exclusive — some implementations combine paginated server fetches with client-side virtual rendering within each page — but for most projects, you will choose one.

Virtual scrolling is the default behavior for large datasets. The grid renders only the rows currently visible in the viewport plus a small buffer above and below. As the user scrolls, rows are recycled in the DOM rather than added and removed — classic windowing technique, same as used in react-window or TanStack Virtual. You do not need to configure anything special; the grid detects dataset size and applies virtual rendering automatically above a configurable threshold. The result is smooth scrolling through 100,000 rows on mid-range hardware.

Pagination requires a bit more setup but gives users a familiar, predictable navigation pattern. SVAR DataGrid includes a built-in Pager component that pairs with the grid:

<script>
  import { DataGrid, Pager } from "svar-datagrid";
  import "svar-datagrid/dist/svar-datagrid.css";

  let data = generateLargeDataset(5000); // your data
  let columns = [...];

  let pageSize = 50;
  let page = 0;
</script>

<div style="height: 500px">
  <DataGrid {data} {columns} bind:page {pageSize} />
</div>
<Pager total={data.length} bind:page {pageSize} />

The bind:page directive keeps the grid and pager in sync reactively — changing the page in the Pager updates the grid immediately with no manual event handling. If you are fetching data server-side, replace total={data.length} with your known total count from the API, and update data on each page change using Svelte’s reactive $: blocks or Svelte 5’s $effect.

Editable Grids: Inline Editing Without the Headache

One of the features that separates SVAR DataGrid from simpler Svelte interactive table components is built-in inline editing. Rather than managing a separate edit modal or a parallel edit state object, you enable editing per-column and let the grid handle the UI — click to select, double-click to edit, Enter/Tab/Escape to confirm or cancel.

let columns = [
  {
    id: "name",
    header: "Name",
    flex: 1,
    editor: "text",          // Enable text input editor
  },
  {
    id: "role",
    header: "Role",
    width: 140,
    editor: "select",        // Enable dropdown editor
    options: [
      { id: "engineer",  label: "Engineer"  },
      { id: "designer",  label: "Designer"  },
      { id: "manager",   label: "Manager"   },
    ],
  },
  {
    id: "startDate",
    header: "Start Date",
    width: 140,
    editor: "date",          // Enable date picker editor
  },
];

Changes made through inline editors update the original data array reactively. If you need to intercept changes before they commit — for validation, transformation, or async saves — the on:change event fires with a detail object containing the row ID, column ID, old value, and new value. You can call event.preventDefault() to block the update and show a validation error in your own UI.

For the specific case of editing large numbers of cells quickly — think spreadsheet-like data entry — the grid also supports keyboard navigation between cells in edit mode. Tab moves to the next editable cell in the row, Enter confirms and moves to the cell below. It is not Excel, but it is close enough for most internal tools, and it requires zero additional configuration.

Real-World Configuration: Putting It All Together

Here is a complete, production-realistic example that combines everything covered so far: sorting, filtering, column resizing, cell templates, and pagination. This is the kind of grid you would build for a user management dashboard or a CRM contacts view.

<script>
  import { DataGrid, Pager } from "svar-datagrid";
  import "svar-datagrid/dist/svar-datagrid.css";

  // Simulated dataset
  let employees = Array.from({ length: 500 }, (_, i) => ({
    id: i + 1,
    name: `Employee ${i + 1}`,
    department: ["Engineering", "Design", "Marketing", "HR"][i % 4],
    salary: 60000 + Math.floor(Math.random() * 80000),
    status: i % 5 === 0 ? "inactive" : "active",
    hired: new Date(2015 + (i % 9), i % 12, (i % 28) + 1)
      .toISOString()
      .split("T")[0],
  }));

  let columns = [
    {
      id: "id",
      header: "#",
      width: 60,
      frozen: true,
    },
    {
      id: "name",
      header: "Name",
      flex: 1,
      sort: true,
      filter: true,
      resize: true,
      frozen: true,
      minWidth: 160,
    },
    {
      id: "department",
      header: "Department",
      width: 160,
      sort: true,
      filter: "select",
      options: [
        { id: "Engineering", label: "Engineering" },
        { id: "Design",      label: "Design"      },
        { id: "Marketing",   label: "Marketing"   },
        { id: "HR",          label: "HR"          },
      ],
    },
    {
      id: "salary",
      header: "Salary",
      width: 130,
      sort: true,
      filter: "number",
      template: (v) => `$${v.toLocaleString("en-US")}`,
    },
    {
      id: "status",
      header: "Status",
      width: 110,
      filter: "select",
      options: [
        { id: "active",   label: "Active"   },
        { id: "inactive", label: "Inactive" },
      ],
      template: (v) => v === "active" ? "✅ Active" : "⛔ Inactive",
    },
    {
      id: "hired",
      header: "Hired",
      width: 120,
      sort: true,
    },
  ];

  let page = 0;
  const pageSize = 25;
</script>

<div style="height: 560px;">
  <DataGrid
    data={employees}
    {columns}
    bind:page
    {pageSize}
    rowHeight={40}
    headerRowHeight={82}
  />
</div>
<Pager total={employees.length} bind:page {pageSize} />

The headerRowHeight={82} gives the filter row enough vertical space when filters are active. The rowHeight={40} provides comfortable row density without wasting screen space. Both values are purely cosmetic and should be adjusted to match your design system’s spacing scale.

Notice that the id and name columns are marked frozen: true. With 500 rows and six columns, horizontal scrolling on smaller viewports would otherwise lose the user’s row context. Freezing the identifier columns is one of those UX details that separates a tool that feels polished from one that merely functions. The frozen columns cast a subtle drop shadow as non-frozen columns scroll beneath them — a nice touch that requires no custom CSS.

Common Pitfalls and How to Avoid Them

Most issues with svar-datagrid that appear in community threads fall into three categories: container height, data reactivity, and CSS conflicts. Each is easy to fix once you know what to look for, and each is frustrating in proportion to how long it takes to diagnose the first time.

The container height issue is the most common: the grid renders invisibly because its parent has no explicit height. The fix is always the same — give the wrapping <div> a height in pixels, vh units, or make it a flex child with flex: 1 in a flex column container. If you are inside a SvelteKit layout with a full-height page structure, height: 100% on the wrapper usually propagates correctly from the <main> tag.

Data reactivity pitfalls arise when you mutate the data array directly — pushing items, splicing, or modifying nested properties — without triggering Svelte’s reactivity. The solution is to reassign: data = [...data, newRow] instead of data.push(newRow). In Svelte 5 with runes, declare your data with let data = $state([...]) and mutations will be tracked automatically, making this class of bug largely disappear.

  • Global CSS resets: Some CSS resets (particularly aggressive ones like Tailwind’s preflight) can strip table-related styles the grid depends on. Scope your reset or add all: revert inside the grid’s container if you see layout oddities.
  • SSR: In SvelteKit with SSR enabled, wrap the DataGrid import in a dynamic import() or use <svelte:component> with a client-only check, since the grid accesses browser APIs on initialization.

The last common issue is performance on initial render with very large datasets and SSR. The grid’s virtual scroller needs DOM measurements to calculate row positions, and those measurements only happen in the browser. If you pass 50,000 rows server-side, the hydration step can be slow. The practical fix is to paginate at the server level and send only the first page of data in the initial response, then fetch subsequent pages on the client.

Frequently Asked Questions

What is the difference between svar-datagrid and wx-svelte-grid?

wx-svelte-grid was the original npm package name for this component, used in versions prior to 2023. svar-datagrid is its direct successor — same maintainers, updated API, better Svelte 5 compatibility, and active development. The two share conceptual DNA but are not drop-in replacements for each other: column prop names changed, the editor API was restructured, and the CSS class naming scheme was updated. If you are starting a new project, use svar-datagrid exclusively. If you are maintaining a project on wx-svelte-grid, a migration guide is available in the SVAR documentation.

How do I enable sorting and filtering in SVAR DataGrid?

Both are column-level features. Add sort: true to any column definition to enable click-to-sort on that column’s header. Add filter: true for a text input filter, filter: "select" for a dropdown, or filter: "number" for a numeric range input. Filters appear as an additional row below the column headers and apply reactively as the user types or selects. No global component prop or external filter state is required — the grid manages filter state internally while keeping your source data array untouched.

Can SVAR DataGrid handle large datasets efficiently?

Yes. The component uses virtual scrolling by default, rendering only the rows visible in the viewport at any given moment. Testing with 100,000-row datasets shows smooth 60fps scrolling on modern hardware. For even larger datasets or when data lives on a server, the grid supports server-side pagination and filtering via event-driven data fetching — you respond to filter and page change events by updating the data prop with the relevant slice from your API.


Join the conversation

Panier 0