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

헤더를 눌러서 정렬하기Click a header to sort

헤더를 누르면 오름차순 → 내림차순 → 정렬 해제 순서로 바뀌어요. Shift+클릭으로 기준을 더하면 다중 정렬이고, 직급처럼 가나다순이 아닌 순서도 값만 바꿔 정렬할 수 있어요.Clicking a header cycles ascending, descending, off. Shift+click adds another sort key, and custom orders such as job grades only need a ranking value.

입문Beginner
직접 써 보기Live preview헤더를 눌러서 정렬하기Click a header to sort

코드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="teamThenSalary">팀 → 연봉 높은 순</button>
    <button type="button" id="byGrade">직급 높은 순</button>
    <button type="button" id="byJoined">입사일 빠른 순</button>
    <button type="button" id="clear">정렬 해제</button>
  </div>
  <div id="grid" style="height: 440px"></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('teamThenSalary').addEventListener('click', () => actions.teamThenSalary(api));
document.getElementById('byGrade').addEventListener('click', () => actions.byGrade(api));
document.getElementById('byJoined').addEventListener('click', () => actions.byJoined(api));
document.getElementById('clear').addEventListener('click', () => actions.clear(api));
example.js
const names = [
  '김민준',
  '이서연',
  '박지호',
  '최유나',
  '정도윤',
  '한소희',
  '오세훈',
  '윤지아',
  '강태양',
  '송하늘',
  '임보라',
  '배준서',
];
const teams = ['개발팀', '디자인팀', '영업팀', '인사팀'];
const GRADES = ['사원', '주임', '대리', '과장', '차장', '부장'];
const memos = [
  '신규 프로젝트 투입',
  '',
  '육아휴직 복귀',
  '',
  '해외 출장 예정',
  '',
  '멘토링 담당',
  '',
];
// '직급'은 가나다순이 아니라 사원 → 부장 순서로 정렬하고 싶어요. 그럴 땐 정렬에 쓰는 값(getValue)을
// 순번으로 돌려주고, 화면에 보이는 글자(formatValue)만 직급 이름으로 바꿔요.
export const options = {
  columns: [
    { id: 'name', title: '이름', width: 100 },
    { id: 'team', title: '팀', width: 110 },
    {
      id: 'grade',
      title: '직급 (서열순)',
      kind: 'number',
      width: 130,
      align: 'start',
      getValue: (row) => GRADES.indexOf(row.grade),
      formatValue: (value) => GRADES[Number(value)] ?? '',
    },
    { id: 'salary', title: '연봉(만원)', kind: 'number', width: 120, align: 'end' },
    { id: 'joined', title: '입사일', width: 120 },
    // sortable: false이면 헤더를 눌러도 정렬되지 않아요.
    { id: 'memo', title: '메모 (정렬 안 됨)', width: 170, sortable: false },
  ],
  rows: Array.from({ length: 12 }, (_, i) => ({
    id: i + 1,
    name: names[i],
    team: teams[(i * 3 + 1) % 4],
    grade: GRADES[(i * 5) % 6],
    salary: 3800 + ((i * 530) % 4200),
    joined: `20${15 + ((i * 7) % 10)}-${String(1 + ((i * 5) % 12)).padStart(2, '0')}-${String(2 + ((i * 11) % 26)).padStart(2, '0')}`,
    memo: memos[i % 8],
  })),
  rowKey: 'id',
};
export function setup(api, log) {
  const titleOf = (id) => api.getColumns().find((c) => c.id === id)?.title ?? id;
  // 정렬 기준을 우선순위 순서대로 풀어서 보여 줘요.
  const off = api.on('sortChanged', ({ sortModel }) => log(sortModel.length === 0
    ? { ko: '정렬 없음 (원래 순서)', en: 'No sort (original order)' }
    : {
      ko: sortModel
        .map((s, i) => `${i + 1}순위 ${titleOf(s.columnId)} ${s.direction === 'asc' ? '▲ 오름차순' : '▼ 내림차순'}`)
        .join(' → '),
      en: sortModel
        .map((s, i) => `#${i + 1} ${titleOf(s.columnId)} ${s.direction === 'asc' ? '▲ ascending' : '▼ descending'}`)
        .join(' → '),
    }));
  return () => off();
}
export const actions = {
  // 코드에서 정렬을 지정해요. 배열 순서가 우선순위예요.
  teamThenSalary: (api) => api.setSortModel([
    { columnId: 'team', direction: 'asc' },
    { columnId: 'salary', direction: 'desc' },
  ]),
  byGrade: (api) => api.setSortModel([{ columnId: 'grade', direction: 'desc' }]),
  byJoined: (api) => api.setSortModel([{ columnId: 'joined', direction: 'asc' }]),
  clear: (api) => api.setSortModel([]),
};

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="teamThenSalary">Team, then salary</button>
    <button type="button" id="byGrade">Highest grade first</button>
    <button type="button" id="byJoined">Earliest hire first</button>
    <button type="button" id="clear">Clear sort</button>
  </div>
  <div id="grid" style="height: 440px"></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('teamThenSalary').addEventListener('click', () => actions.teamThenSalary(api));
document.getElementById('byGrade').addEventListener('click', () => actions.byGrade(api));
document.getElementById('byJoined').addEventListener('click', () => actions.byJoined(api));
document.getElementById('clear').addEventListener('click', () => actions.clear(api));
example.js
const names = [
  'Liam Carter',
  'Emma Stone',
  'Noah Brooks',
  'Olivia Reed',
  'Ethan Hall',
  'Ava Morgan',
  'Mason Gray',
  'Mia Foster',
  'Lucas Bell',
  'Sophia Ward',
  'Logan Price',
  'Chloe Ross',
];
const teams = ['Dev', 'Design', 'Sales', 'HR'];
const GRADES = ['Junior', 'Associate', 'Senior', 'Lead', 'Manager', 'Director'];
const memos = [
  'Joining a new project',
  '',
  'Back from parental leave',
  '',
  'Overseas trip planned',
  '',
  'Mentoring duty',
  '',
];
// We want 'Grade' sorted Junior -> Director, not alphabetically. So the sort value (getValue)
// returns the rank number, and only the displayed text (formatValue) is turned into the grade name.
export const options = {
  columns: [
    { id: 'name', title: 'Name', width: 100 },
    { id: 'team', title: 'Team', width: 110 },
    {
      id: 'grade',
      title: 'Grade (by rank)',
      kind: 'number',
      width: 130,
      align: 'start',
      getValue: (row) => GRADES.indexOf(row.grade),
      formatValue: (value) => GRADES[Number(value)] ?? '',
    },
    { id: 'salary', title: 'Salary ($)', kind: 'number', width: 120, align: 'end' },
    { id: 'joined', title: 'Joined', width: 120 },
    // With sortable: false, clicking the header does not sort.
    { id: 'memo', title: 'Memo (not sortable)', width: 170, sortable: false },
  ],
  rows: Array.from({ length: 12 }, (_, i) => ({
    id: i + 1,
    name: names[i],
    team: teams[(i * 3 + 1) % 4],
    grade: GRADES[(i * 5) % 6],
    salary: 38000 + ((i * 530) % 4200) * 10,
    joined: `20${15 + ((i * 7) % 10)}-${String(1 + ((i * 5) % 12)).padStart(2, '0')}-${String(2 + ((i * 11) % 26)).padStart(2, '0')}`,
    memo: memos[i % 8],
  })),
  rowKey: 'id',
};
export function setup(api, log) {
  const titleOf = (id) => api.getColumns().find((c) => c.id === id)?.title ?? id;
  // List the sort keys in priority order.
  const off = api.on('sortChanged', ({ sortModel }) => log(sortModel.length === 0
    ? 'No sort (original order)'
    : sortModel
      .map((s, i) => `#${i + 1} ${titleOf(s.columnId)} ${s.direction === 'asc' ? '▲ ascending' : '▼ descending'}`)
      .join(' → ')));
  return () => off();
}
export const actions = {
  // Set the sort from code. The array order is the priority.
  teamThenSalary: (api) => api.setSortModel([
    { columnId: 'team', direction: 'asc' },
    { columnId: 'salary', direction: 'desc' },
  ]),
  byGrade: (api) => api.setSortModel([{ columnId: 'grade', direction: 'desc' }]),
  byJoined: (api) => api.setSortModel([{ columnId: 'joined', direction: 'asc' }]),
  clear: (api) => api.setSortModel([]),
};