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

행을 골라 위·아래로 옮기기Move a selected row up or down

결재선처럼 순서가 곧 데이터인 목록에서, 행을 고른 뒤 버튼으로 한 칸씩 위아래로 옮겨요. 정렬은 꺼 두고, 순서를 바꾼 목록을 새로 넣어서 바꿔요. 옮긴 뒤에도 그 행은 선택된 채로 남아요.For lists where order is the data, such as an approval route, select a row and move it one step with buttons. Sorting is off and the reordered list is put in again. The row stays selected after the move.

입문Beginner
직접 써 보기Live preview행을 골라 위·아래로 옮기기Move a selected row up or down

코드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="moveUp">위로</button>
    <button type="button" id="moveDown">아래로</button>
  </div>
  <div id="grid" style="height: 320px"></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('moveUp').addEventListener('click', () => actions.moveUp(api));
document.getElementById('moveDown').addEventListener('click', () => actions.moveDown(api));
example.js
// 순서 자체가 데이터인 목록(결재선, 점검표)이라 정렬은 꺼 두었어요.
export const options = {
  columns: [
    { id: 'step', title: '단계', width: 200, sortable: false },
    { id: 'owner', title: '담당', width: 130, sortable: false },
  ],
  rows: [
    { id: 1, step: '기안 작성', owner: '김민준' },
    { id: 2, step: '팀장 검토', owner: '이서연' },
    { id: 3, step: '재무 확인', owner: '박지호' },
    { id: 4, step: '임원 승인', owner: '최유나' },
    { id: 5, step: '결과 통보', owner: '정도윤' },
  ],
  rowKey: 'id',
  selection: 'single',
  showRowNumbers: true,
};
// 데이터 값 뒤에 붙는 조사는 마지막 글자의 받침에 맞춰 골라요(숫자는 읽는 소리 기준).
const batchim = (word) => {
  const ch = word.trim().slice(-1);
  const digit = '0123456789'.indexOf(ch);
  if (digit >= 0)
    return [21, 8, 0, 16, 0, 0, 1, 8, 8, 0][digit] ?? 0; // 영 일 이 삼 사 오 육 칠 팔 구
  const code = ch.charCodeAt(0) - 0xac00;
  return code >= 0 && code <= 11171 ? code % 28 : 0;
};
const eulReul = (word) => (batchim(word) ? '을' : '를');
let say = () => { };
export function setup(_api, log) {
  say = log;
  return () => { };
}
// 그리드가 행 끌기를 지원하지 않아서, 행을 고른 뒤 버튼으로 옮겨요. 행 순서는 setRows에 순서를 바꾼 배열을 주면 바뀌어요.
function move(api, offset) {
  const key = api.getSelectedKeys()[0];
  if (key === undefined)
    return say({ ko: '먼저 옮길 행을 눌러 주세요', en: 'Click the row to move first' });
  const rows = [...api.getRows()];
  const from = rows.findIndex((row) => row.id === key);
  const to = from + offset;
  if (to < 0 || to >= rows.length)
    return say({
      ko: `이미 맨 ${offset < 0 ? '위' : '아래'}에 있어요`,
      en: `Already at the ${offset < 0 ? 'top' : 'bottom'}`,
    });
  rows.splice(to, 0, ...rows.splice(from, 1));
  api.setRows(rows);
  api.setSelectedKeys([key]);
  say({
    ko: `'${rows[to]?.step}'${eulReul(rows[to]?.step ?? '')} ${to + 1}번째로 옮겼어요`,
    en: `Moved '${rows[to]?.step}' to position ${to + 1}`,
  });
}
export const actions = {
  moveUp: (api) => move(api, -1),
  moveDown: (api) => move(api, 1),
};

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="moveUp">Up</button>
    <button type="button" id="moveDown">Down</button>
  </div>
  <div id="grid" style="height: 320px"></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('moveUp').addEventListener('click', () => actions.moveUp(api));
document.getElementById('moveDown').addEventListener('click', () => actions.moveDown(api));
example.js
// The order itself is the data (approval chain, checklist), so sorting is turned off.
export const options = {
  columns: [
    { id: 'step', title: 'Step', width: 200, sortable: false },
    { id: 'owner', title: 'Owner', width: 140, sortable: false },
  ],
  rows: [
    { id: 1, step: 'Draft request', owner: 'Liam Carter' },
    { id: 2, step: 'Manager review', owner: 'Emma Stone' },
    { id: 3, step: 'Finance check', owner: 'Noah Reed' },
    { id: 4, step: 'Executive approval', owner: 'Olivia Hayes' },
    { id: 5, step: 'Notify result', owner: 'Ethan Brooks' },
  ],
  rowKey: 'id',
  selection: 'single',
  showRowNumbers: true,
};
let say = () => { };
export function setup(_api, log) {
  say = log;
  return () => { };
}
// The grid does not support row dragging here, so select a row and move it with buttons. The row order changes
// when setRows receives a reordered array.
function move(api, offset) {
  const key = api.getSelectedKeys()[0];
  if (key === undefined)
    return say('Click the row to move first');
  const rows = [...api.getRows()];
  const from = rows.findIndex((row) => row.id === key);
  const to = from + offset;
  if (to < 0 || to >= rows.length)
    return say(`Already at the ${offset < 0 ? 'top' : 'bottom'}`);
  rows.splice(to, 0, ...rows.splice(from, 1));
  api.setRows(rows);
  api.setSelectedKeys([key]);
  say(`Moved '${rows[to]?.step}' to position ${to + 1}`);
}
export const actions = {
  moveUp: (api) => move(api, -1),
  moveDown: (api) => move(api, 1),
};