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

훅으로 키와 선택 다루기Handle keys and selection with hooks

hooks.onKeyDown이 true를 돌려주면 그리드가 그 키(여기서는 Delete)를 처리하지 않고, hooks.canSelect가 false면 그 셀은 선택되지 않아요. hooks.rowRendered는 행 요소가 채워질 때마다 불려요.When hooks.onKeyDown returns true the grid ignores that key (Delete here), and when hooks.canSelect returns false the cell is not selected. hooks.rowRendered runs each time a row element is filled.

활용Intermediate
직접 써 보기Live preview훅으로 키와 선택 다루기Handle keys and selection with hooks

코드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="focusName">이름 칸 포커스</button>
    <button type="button" id="selectName">이름 칸 선택</button>
    <button type="button" id="selectId">번호 칸 선택</button>
  </div>
  <div id="grid" style="height: 220px"></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('focusName').addEventListener('click', () => actions.focusName(api));
document.getElementById('selectName').addEventListener('click', () => actions.selectName(api));
document.getElementById('selectId').addEventListener('click', () => actions.selectId(api));
example.js
const rows = [
  { id: 1, name: '김서연', team: '개발' },
  { id: 2, name: '이준호', team: '디자인' },
  { id: 3, name: '박민지', team: '개발' },
  { id: 4, name: '최도윤', team: '영업' },
];
let log = () => undefined;
// onKeyDown이 true를 돌려주면 그리드는 그 키를 처리하지 않아요(여기서는 Delete). canSelect는 '번호' 칸의 셀 선택을 막아요.
// rowRendered는 행 요소가 채워질 때마다 불려서 팀 이름을 data 속성으로 달아 줘요(스타일링 훅).
export const options = {
  columns: [
    { id: 'id', title: '번호', kind: 'number', width: 70 },
    { id: 'name', title: '이름', width: 130, editable: true },
    { id: 'team', title: '팀', width: 110 },
  ],
  rows,
  rowKey: 'id',
  cellSelection: 'multiple',
  hooks: {
    onKeyDown: ({ event, rowKey, columnId }) => {
      if (event.key !== 'Delete')
        return false;
      log({
        ko: `Delete를 막았어요 (${rowKey}/${columnId})`,
        en: `Delete is ignored (${rowKey}/${columnId})`,
      });
      return true;
    },
    canSelect: ({ kind, rowKey, columnId }) => {
      const allowed = !(kind === 'cell' && columnId === 'id');
      if (!allowed)
        log({
          ko: `${rowKey}번의 번호 칸은 고를 수 없어요`,
          en: `The id cell of row ${rowKey} cannot be selected`,
        });
      return allowed;
    },
    rowRendered: ({ rowKey, element }) => {
      element.dataset.team = rows.find((r) => r.id === rowKey)?.team ?? '';
    },
  },
};
export function setup(_api, write) {
  log = write;
  return () => {
    log = () => undefined;
  };
}
export const actions = {
  selectName: (api) => api.selectCells({ rowKey: 2, columnId: 'name' }),
  selectId: (api) => api.selectCells({ rowKey: 2, columnId: 'id' }),
  focusName: (api) => api.focusCell(1, 'name'),
};

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="focusName">Focus name cell</button>
    <button type="button" id="selectName">Select name cell</button>
    <button type="button" id="selectId">Select id cell</button>
  </div>
  <div id="grid" style="height: 220px"></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('focusName').addEventListener('click', () => actions.focusName(api));
document.getElementById('selectName').addEventListener('click', () => actions.selectName(api));
document.getElementById('selectId').addEventListener('click', () => actions.selectId(api));
example.js
const rows = [
  { id: 1, name: 'Liam Carter', team: 'Dev' },
  { id: 2, name: 'Emma Stone', team: 'Design' },
  { id: 3, name: 'Olivia Park', team: 'Dev' },
  { id: 4, name: 'Noah Kim', team: 'Sales' },
];
let log = () => undefined;
// If onKeyDown returns true, the grid does not handle that key (Delete here). canSelect blocks cell selection in the 'No.' column.
// rowRendered is called whenever a row element is filled, and attaches the team name as a data attribute (a styling hook).
export const options = {
  columns: [
    { id: 'id', title: 'No.', kind: 'number', width: 70 },
    { id: 'name', title: 'Name', width: 140, editable: true },
    { id: 'team', title: 'Team', width: 110 },
  ],
  rows,
  rowKey: 'id',
  cellSelection: 'multiple',
  hooks: {
    onKeyDown: ({ event, rowKey, columnId }) => {
      if (event.key !== 'Delete')
        return false;
      log(`Delete is ignored (${rowKey}/${columnId})`);
      return true;
    },
    canSelect: ({ kind, rowKey, columnId }) => {
      const allowed = !(kind === 'cell' && columnId === 'id');
      if (!allowed)
        log(`The id cell of row ${rowKey} cannot be selected`);
      return allowed;
    },
    rowRendered: ({ rowKey, element }) => {
      element.dataset.team = rows.find((r) => r.id === rowKey)?.team ?? '';
    },
  },
};
export function setup(_api, write) {
  log = write;
  return () => {
    log = () => undefined;
  };
}
export const actions = {
  selectName: (api) => api.selectCells({ rowKey: 2, columnId: 'name' }),
  selectId: (api) => api.selectCells({ rowKey: 2, columnId: 'id' }),
  focusName: (api) => api.focusCell(1, 'name'),
};