TOAST UI Grid Documentation

repository·master·Indexed 25 days ago

https://github.com/nhn/tui.grid

A powerful data grid component for displaying, editing, adding, and deleting large datasets. It features a core Plain JavaScript library (tui-grid) with official wrappers for React (@toast-ui/react-grid) and Vue (@toast-ui/vue-grid). Key capabilities include tree data, summary functions, custom editors and renderers, data source binding for remote data, and support for complex columns, frozen columns, and pagination.

Tokens
38.1K
Snippets
124
Records
169
Agent score
80%

What's inside TOAST UI Grid

  1. Available TOAST UI Grid packages

    master

    TOAST UI Grid provides different packages depending on your preferred framework:

    • tui-grid: The core Plain JavaScript component.
    • @toast-ui/vue-grid: A wrapper component for Vue applications.
    • @toast-ui/react-grid: A wrapper component for React applications.
  2. Implement advanced TOAST UI Grid features

    master

    TOAST UI Grid provides several advanced features that can be implemented via specific tutorials:

    • Columns: Configure Complex Columns or define Relation Between Columns.
    • Customization: Create a Custom Editor, Custom Renderer, or Custom Event handlers.
    • UI/UX: Implement Themes, DatePicker, Keymap configurations, or Clipboard functionality.
    • Data & Structure: Use a Data Source, implement Tree structures, or manage Row Span and Frozen Columns.
    • Grid Layout: Configure Row Headers, Sort, Pagination, Filter, and Validation.
    • Sizing: Learn about Setting width, height for the grid container.
  3. Disable Auto Summary for specific columns

    master

    By default, providing a template function enables auto-calculation. You can disable this behavior using the useAutoSummary property within columnContent or defaultContent.

    Set useAutoSummary: false if you want to provide a custom template that does not rely on the Grid's automatic calculations.

    Additionally, if you assign a plain HTML string directly to a column in columnContent or defaultContent (instead of an object with a template function), the Grid automatically sets useAutoSummary: false to prevent unnecessary calculations.

    // Disabling auto summary via property
    const grid = new Grid({
      // ...,
      summary: {
        columnContent: {
          col1: {
            useAutoSummary: false,
            template(summary) {
              return 'max: ' + summary.max + '<br>min: ' + summary.min;
            }
          }
        },
        defaultContent: {
          useAutoSummary: false,
          template(summary) {
            return 'default: ' + summary.sum;
          }
        }
      }
    });
    
    // Disabling auto summary by providing a static string
    const gridStatic = new Grid({
      // ...,
      summary: {
        columnContent: {
          col1: 'col1 content'
        },
        defaultContent: 'static content'
      }
    });
  4. Implement a Custom Renderer for cell UI customization

    master

    TOAST UI Grid allows you to replace the default cell rendering with a custom UI by providing a CellRenderer class. This is more powerful than a formatter because it allows you to inject actual DOM elements (like inputs, buttons, or sliders) into the cell.

    CellRenderer Interface

    To create a custom renderer, implement a class with the following structure:

    • constructor(props): Called when the cell (<td>) is added to the DOM. The props object contains:
      • grid: The Grid instance.
      • rowKey: The rowKey of the current row.
      • columnInfo: Information about the column, including any custom renderer.options.
      • value: The current cell value.
    • getElement(): Required. Returns the root DOM element of the custom renderer. This element is automatically inserted into the cell.
    • render(props): Required. Used to synchronize the cell's value with the UI. This is called whenever the cell value changes.
    • mounted(props): Optional. Called immediately after the root element is mounted to the DOM. Useful for initializing third-party libraries or input elements.
    • focused(props): Optional. Called every time the cell receives focus.
    class CustomSliderRenderer {
      constructor(props) {
        const el = document.createElement('input');
        const { min, max } = props.columnInfo.renderer.options;
    
        el.type = 'range';
        el.min = String(min);
        el.max = String(max);
    
        el.addEventListener('mousedown', (ev) => {
          ev.stopPropagation();
        });
    
        this.el = el;
        this.render(props);
      }
    
      getElement() {
        return this.el;
      }
    
      render(props) {
        this.el.value = String(props.value);
      }
    }
  5. Understand API behavior differences in Pagination modes

    master

    The behavior of certain row manipulation APIs changes depending on whether you are using Client Pagination or Data Source synced pagination:

    APIClient PaginationData Source Synced Pagination
    appendRowAppends to the bottom of all dataAppends to the bottom of the current page
    prependRowInserts at the beginning of all dataInserts at the beginning of the current page
    removeRowRemoves from all dataRemoves from the current page
  6. Customize Row Header with header and renderer

    master

    You can customize the visual representation of row headers using header or renderer:

    • header: Accepts an HTML string to be placed in the header section (e.g., for a custom 'Select All' checkbox).
    • renderer: Accepts a Custom Renderer constructor function to customize the row header section for every individual row. This is useful for implementing custom logic or UI elements like radio buttons (which were discontinued in v4.0).
    // Example: Customizing the header with an HTML string
    const grid = new Grid({
      // ...,
      rowHeaders: [
        {
          type: 'checkbox',
          header: `
            <label for="all-checkbox" class="checkbox">
              <input type="checkbox" id="all-checkbox" class="hidden-input" name="_checked" />
              <span class="custom-input"></span>
            </label>
          `
        }
      ]
    });
    
    // Example: Using a Custom Renderer
    class CheckboxRenderer {
      constructor(props) {
        const { grid, rowKey } = props;
        // ... implementation logic ...
        this.el = label;
        this.render(props);
      }
    
      getElement() {
        return this.el;
      }
    
      render(props) {
        const hiddenInput = this.el.querySelector('.hidden-input');
        const checked = Boolean(props.value);
        hiddenInput.checked = checked;
      }
    }
    
    const grid = new tui.Grid({
      el: document.getElementById('grid'),
      data,
      rowHeaders: [
        {
          type: 'checkbox',
          renderer: {
            type: CheckboxRenderer
          }
        }
      ]
    });
  7. Core Data Transformation Features

    master

    TOAST UI Grid acts as a data transformer with several key capabilities:

    • Flexible Data Display: Supports appending units to data and using html to render images or links.
    • Summary Function: Automatically calculates and displays totals, averages, maximums, and minimums for multiple rows, updating dynamically as values change.
    • Tree Data: Supports hierarchical data representation (available since version 3).
    • Custom Editing: Provides built-in support for various input types like text, select box, checkbox, and radio button. You can also implement a Custom Editor for specialized requirements.
  8. Sort multiple columns simultaneously

    master

    TOAST UI Grid (v4.2.0+) supports multiple column sorting. To use this feature, click a column's sort button while holding down the Cmd (macOS) or Ctrl (Windows/Linux) key. The columns will be sorted in the order they were clicked.

    If you click a sort button without holding the modifier key, all previous sorting is cancelled, and only the newly selected column is sorted.

  9. How sorting works with Infinite Scroll

    master

    When using infinite scroll synchronized with a Data Source, sorting behaves differently than standard pagination:

    • No server communication required: Unlike pagination, you do not need to set useClientSort: false to force server-side sorting.
    • Local sorting: When a user sorts, only the currently visible (loaded) data is sorted. This avoids unnecessary server requests for the entire dataset.
  10. Understand reactive vs non-reactive props

    master

    Not all props in the React wrapper are reactive. When a parent component re-renders, only specific props will trigger the underlying grid to update via setter methods.

    Supported reactive props:

    • data (via setData)
    • columns (via setColumns)
    • bodyHeight (via setBodyHeight)
    • frozenColumnCount (via setFrozenColumnCount)

    To prevent a prop from triggering a re-render, you can use the oneTimeBindingProps array to disable reactivity for specific keys.

    const MyComponent = () => (
      <Grid
        data={data}
        columns={columns}
        bodyHeight={100}
        frozenColumnCount={2}
        oneTimeBindingProps={['data', 'columns']}
      />
    );
  11. Use Auto Summary to calculate column statistics

    master

    When you provide a template function within columnContent or defaultContent, TOAST UI Grid automatically calculates summary statistics whenever column values change.

    The template function receives a summary object as an argument, which contains the following properties:

    • sum: Sum of the column values.
    • avg: Average value of the column.
    • min: Minimum value in the column.
    • max: Maximum value in the column.
    • cnt: Number of rows.

    The template function must return an HTML string used to render the summary cell.

    const grid = new Grid({
      // ...,
      summary: {
        columnContent: {
          col1: {
            template(summary) {
              return 'sum: ' + summary.sum + '<br>avg: ' + summary.avg;
            }
          },
          col2: {
            template(summary) {
              return 'max: ' + summary.max + '<br>min: ' + summary.min;
            }
          }
        },
        defaultContent: {
          template(summary) {
            return 'default: ' + summary.sum;
          }
        }
      }
    })
  12. Use the GridEvent object in event handlers

    master

    When an event is triggered, the handler receives a GridEvent instance. This object provides context about the event and allows you to control event behavior.

    Key properties and methods:

    • rowKey: The identifier for the row involved in the event.
    • columnName: The name of the column involved in the event.
    • targetType: The type of the target element.
    • nativeEvent: The browser's native event object (e.g., MouseEvent).
    • stop(): A method to prevent the default action of the event (e.g., preventing a cell from being selected).
    // Accessing event details
    grid.on('click', function(ev) {
      if (ev.rowKey === 3 && ev.columnName === 'col1') {
        // do something
      }
    });
    
    // Preventing default action
    grid.on('click', function(ev) {
      if (ev.rowKey === 3) {
        ev.stop();  
      }
    });
    
    // Accessing native browser event
    grid.on('mousedown', function(ev) {
      console.log(ev.nativeEvent);
    });