본문으로 건너뛰기Skip to content
예제 첫화면Examples home

나만의 조건으로 걸러 보기Filter by your own rule

'이름이 연으로 끝나는 사람', '가격이 1로 시작', '2024년 9월 주문'처럼 기본 조건에 없는 규칙도 걸러낼 수 있어요. 값을 계산해서 만든 컬럼을 하나 두고 그 컬럼에 조건을 걸면 돼요.Rules that are not built in, such as names ending in a syllable, prices starting with 1 or orders from September 2024, are easy: add a computed column and filter on it.

활용Intermediate
직접 써 보기Live preview나만의 조건으로 걸러 보기Filter by your own rule

코드Code

탭을 골라 코드를 복사하세요. 위 화면은 이 코드를 그대로 실행한 결과예요.Pick a tab and copy the code. The preview above runs exactly this code.

이 화면은 새 모양 옵션을 켠 모양이에요: density: 'spacious', iconStyle: 'soft', motion: true (코드에 없으면 기본 모양으로 보여요)This preview has the new-look options on: density: 'spacious', iconStyle: 'soft', motion: true (without them in your code you get the default look)

빌드 도구(Vite 등)를 쓰는 프로젝트용 모듈 파일이에요. 설치 없이 바로 돌려 보려면 HTML 탭이나 직접 해보기를 쓰세요.

버튼을 누르면 이 예제의 코드가 StackBlitz나 CodeSandbox로 전송돼요. 누르기 전에는 아무것도 보내지 않아요.

index.html
<div id="app">
  <div class="toolbar">
    <button type="button" id="endsWith">이름이 '연'으로 끝나는 사람</button>
    <button type="button" id="multi">이서연이 산 웹캠</button>
    <button type="button" id="lead">가격이 1로 시작</button>
    <button type="button" id="month">2024년 9월 주문</button>
    <button type="button" id="clear">필터 지우기</button>
  </div>
  <div id="grid" style="height: 540px"></div>
</div>
<script type="module" src="./main.js"></script>
main.js
import { createGrid } from 'maxgrid';
import { actions, options, setup } from './example';
const api = createGrid(document.getElementById('grid'), options);
setup(api, console.log);
document.getElementById('endsWith').addEventListener('click', () => actions.endsWith(api));
document.getElementById('multi').addEventListener('click', () => actions.multi(api));
document.getElementById('lead').addEventListener('click', () => actions.lead(api));
document.getElementById('month').addEventListener('click', () => actions.month(api));
document.getElementById('clear').addEventListener('click', () => actions.clear(api));
example.js
const customers = ['김민준', '이서연', '박지호', '최유나', '정도윤', '한소희'];
const products = ['노트북', '모니터', '무선 키보드', '웹캠', '도킹 스테이션'];
const pad = (n) => String(n).padStart(2, '0');
// "가격이 1로 시작", "9월 주문"처럼 값 그대로는 비교할 수 없는 조건은 계산해서 만든 컬럼(getValue)으로 풀어요.
// 계산 컬럼은 일반 컬럼처럼 필터에 쓸 수 있어서, 조건을 코드로 만들 필요 없이 같은 필터 모델로 걸러져요.
export const options = {
  columns: [
    { id: 'customer', title: '고객명', width: 110 },
    { id: 'product', title: '상품', width: 150 },
    {
      id: 'price',
      title: '가격(원)',
      kind: 'number',
      width: 120,
      align: 'end',
      formatValue: (value) => Number(value).toLocaleString('ko-KR'),
    },
    // 계산 컬럼 1: 가격의 맨 앞 숫자
    { id: 'lead', title: '가격 앞자리', width: 110, getValue: (row) => String(row.price)[0] ?? '' },
    {
      id: 'ordered',
      title: '주문일',
      kind: 'date',
      width: 120,
      formatValue: (value) => value instanceof Date
        ? `${value.getFullYear()}-${pad(value.getMonth() + 1)}-${pad(value.getDate())}`
        : '',
    },
    // 계산 컬럼 2: 주문한 달(예: 2024-09)
    {
      id: 'month',
      title: '주문월',
      width: 100,
      getValue: (row) => `${row.ordered.getFullYear()}-${pad(row.ordered.getMonth() + 1)}`,
    },
  ],
  rows: Array.from({ length: 14 }, (_, i) => ({
    id: i + 1,
    customer: customers[i % 6],
    product: products[(i * 3) % 5],
    price: 9900 + ((i * 187000) % 1900000),
    ordered: new Date(2024, 7 + (i % 3), 3 + ((i * 5) % 24)),
  })),
  rowKey: 'id',
};
// 같은 버튼을 한 번 더 누르면 필터를 풀어요(참조 데모와 같은 동작).
const PRESETS = {
  endsWith: [{ columnId: 'customer', operator: 'endsWith', value: '연' }],
  multi: [
    { columnId: 'customer', operator: 'equals', value: '이서연' },
    { columnId: 'product', operator: 'equals', value: '웹캠' },
  ],
  lead: [{ columnId: 'lead', operator: 'equals', value: '1' }],
  month: [{ columnId: 'month', operator: 'equals', value: '2024-09' }],
};
let active = null;
const toggle = (api, key) => {
  active = active === key ? null : key;
  api.setFilterModel(active ? { match: 'all', items: PRESETS[active] } : null);
};
export function setup(api, log) {
  active = null;
  const off = api.on('filterChanged', ({ filterModel }) => log({
    ko: filterModel === null
      ? '필터 해제: 모든 행이 보여요'
      : `필터 적용 → 보이는 행 ${api.getVisibleRowCount()}개`,
    en: filterModel === null
      ? 'Filter cleared: all rows are visible'
      : `Filter applied → ${api.getVisibleRowCount()} rows visible`,
  }));
  return () => off();
}
export const actions = {
  endsWith: (api) => toggle(api, 'endsWith'),
  multi: (api) => toggle(api, 'multi'),
  lead: (api) => toggle(api, 'lead'),
  month: (api) => toggle(api, 'month'),
  clear: (api) => {
    active = null;
    api.setFilterModel(null);
  },
};

Module files for a project with a bundler such as Vite. To run it with no setup, use the HTML tab or Try it.

When you click, the example code is sent to StackBlitz or CodeSandbox. Nothing is sent before you click.

index.html
<div id="app">
  <div class="toolbar">
    <button type="button" id="endsWith">Name ends with Stone</button>
    <button type="button" id="multi">Emma Stone's webcams</button>
    <button type="button" id="lead">Price starts with 1</button>
    <button type="button" id="month">Orders in Sept 2024</button>
    <button type="button" id="clear">Clear filter</button>
  </div>
  <div id="grid" style="height: 540px"></div>
</div>
<script type="module" src="./main.js"></script>
main.js
import { createGrid } from 'maxgrid';
import { actions, options, setup } from './example';
const api = createGrid(document.getElementById('grid'), options);
setup(api, console.log);
document.getElementById('endsWith').addEventListener('click', () => actions.endsWith(api));
document.getElementById('multi').addEventListener('click', () => actions.multi(api));
document.getElementById('lead').addEventListener('click', () => actions.lead(api));
document.getElementById('month').addEventListener('click', () => actions.month(api));
document.getElementById('clear').addEventListener('click', () => actions.clear(api));
example.js
const customers = [
  'Liam Carter',
  'Emma Stone',
  'Noah Kim',
  'Olivia Park',
  'Ethan Brooks',
  'Sophia Lee',
];
const products = ['Laptop', 'Monitor', 'Wireless Keyboard', 'Webcam', 'Docking Station'];
const pad = (n) => String(n).padStart(2, '0');
// Conditions you cannot compare on the raw value, such as "price starts with 1" or "ordered in September", are solved with computed columns (getValue).
// A computed column can be filtered like any other column, so the same filter model works without building the condition in code.
export const options = {
  columns: [
    { id: 'customer', title: 'Customer', width: 130 },
    { id: 'product', title: 'Product', width: 170 },
    {
      id: 'price',
      title: 'Price ($)',
      kind: 'number',
      width: 120,
      align: 'end',
      formatValue: (value) => `$${Number(value).toLocaleString('en-US')}`,
    },
    // Computed column 1: the first digit of the price
    {
      id: 'lead',
      title: 'Price lead digit',
      width: 180,
      getValue: (row) => String(row.price)[0] ?? '',
    },
    {
      id: 'ordered',
      title: 'Order date',
      kind: 'date',
      width: 120,
      formatValue: (value) => value instanceof Date
        ? `${value.getFullYear()}-${pad(value.getMonth() + 1)}-${pad(value.getDate())}`
        : '',
    },
    // Computed column 2: the month of the order (for example 2024-09)
    {
      id: 'month',
      title: 'Order month',
      width: 140,
      getValue: (row) => `${row.ordered.getFullYear()}-${pad(row.ordered.getMonth() + 1)}`,
    },
  ],
  rows: Array.from({ length: 14 }, (_, i) => ({
    id: i + 1,
    customer: customers[i % 6],
    product: products[(i * 3) % 5],
    price: 10 + ((i * 187) % 1900),
    ordered: new Date(2024, 7 + (i % 3), 3 + ((i * 5) % 24)),
  })),
  rowKey: 'id',
};
// Pressing the same button again clears the filter (same behavior as the reference demo).
const PRESETS = {
  endsWith: [{ columnId: 'customer', operator: 'endsWith', value: 'Stone' }],
  multi: [
    { columnId: 'customer', operator: 'equals', value: 'Emma Stone' },
    { columnId: 'product', operator: 'equals', value: 'Webcam' },
  ],
  lead: [{ columnId: 'lead', operator: 'equals', value: '1' }],
  month: [{ columnId: 'month', operator: 'equals', value: '2024-09' }],
};
let active = null;
const toggle = (api, key) => {
  active = active === key ? null : key;
  api.setFilterModel(active ? { match: 'all', items: PRESETS[active] } : null);
};
export function setup(api, log) {
  active = null;
  const off = api.on('filterChanged', ({ filterModel }) => log(filterModel === null
    ? 'Filter cleared: all rows are visible'
    : `Filter applied → ${api.getVisibleRowCount()} rows visible`));
  return () => off();
}
export const actions = {
  endsWith: (api) => toggle(api, 'endsWith'),
  multi: (api) => toggle(api, 'multi'),
  lead: (api) => toggle(api, 'lead'),
  month: (api) => toggle(api, 'month'),
  clear: (api) => {
    active = null;
    api.setFilterModel(null);
  },
};