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

조건에 맞는 칸만 꾸미기Style the cells that match a rule

데이터를 읽어 조건에 맞는 칸만 setCellStyles로 한꺼번에 꾸며요(다시 그리기는 한 번). 점수를 고치면 그 칸만 setCellStyle로 다시 판단해요. 콜백(cellStyle)과 달리 앱이 원하는 때에 원하는 칸만 정해요.Read your data and style only the matching cells in one setCellStyles call (a single repaint). When a score is edited only that cell is re-evaluated with setCellStyle. Unlike a cellStyle callback, the app decides when and which cells.

활용Intermediate
직접 써 보기Live preview조건에 맞는 칸만 꾸미기Style the cells that match a 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">
    <select aria-label="기준 점수" id="limit">
      <option value="50">50점 이상</option>
      <option value="70" selected>70점 이상</option>
      <option value="90">90점 이상</option>
    </select>
    <button type="button" id="clear">점수 칸 스타일 지우기</button>
  </div>
  <div id="grid" style="height: 380px"></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('limit').addEventListener('change', (event) => actions.limit(api, event.target.value));
document.getElementById('clear').addEventListener('click', () => actions.clear(api));
example.js
const en = document.documentElement.dataset.lang === 'en';
const names = en
  ? ['Alex', 'Blair', 'Casey', 'Drew', 'Emery', 'Finn', 'Gray', 'Harper']
  : ['김서연', '이준호', '박민지', '최도윤', '정하은', '한지우', '오세훈', '윤아름'];
export const options = {
  columns: [
    { id: 'name', title: en ? 'Name' : '이름', width: 120 },
    {
      id: 'score',
      title: en ? 'Score' : '점수',
      kind: 'number',
      width: 90,
      editable: true,
      sortable: true,
    },
    { id: 'note', title: en ? 'Note' : '비고', width: 140 },
  ],
  rows: names.map((name, i) => ({ id: i + 1, name, score: 40 + ((i * 13) % 60), note: '' })),
  rowKey: 'id',
};
let say = () => { };
let limit = 70;
/** 기준을 넘은 점수 칸에만 스타일을 얹는다: 한 번에 setCellStyles로 넣으니 다시 그리기는 한 번이에요. */
function paint(api) {
  const entries = api.getRows().map((row) => ({
    rowKey: row.id,
    columnId: 'score',
    style: row.score >= limit
      ? {
        className: 'high',
        style: { backgroundColor: '#d3f9d8', color: '#0b6b2f', fontWeight: 700 },
      }
      : null,
  }));
  api.setCellStyles(entries);
  return entries.filter((e) => e.style !== null).length;
}
export function setup(api, log) {
  say = log;
  paint(api);
  // 점수를 고치면 그 행만 다시 판단해요.
  const off = api.on('editCommitted', ({ rowKey }) => {
    const row = api.getRowByKey(rowKey);
    if (row)
      api.setCellStyle(rowKey, 'score', row.score >= limit
        ? {
          className: 'high',
          style: { backgroundColor: '#d3f9d8', color: '#0b6b2f', fontWeight: 700 },
        }
        : null);
  });
  return () => {
    off();
  };
}
export const actions = {
  limit: (api, value) => {
    limit = Number(value) || 70;
    const count = paint(api);
    say({
      ko: `${limit}점 이상 ${count}칸에 스타일을 얹었어요`,
      en: `Styled ${count} cells at ${limit} or more`,
    });
  },
  clear: (api) => {
    api.clearCellStyles({ columnIds: ['score'] });
    say({ ko: '점수 칸 스타일을 지웠어요', en: 'Cleared the score styles' });
  },
};

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">
    <select aria-label="Limit" id="limit">
      <option value="50">50 or more</option>
      <option value="70" selected>70 or more</option>
      <option value="90">90 or more</option>
    </select>
    <button type="button" id="clear">Clear score styles</button>
  </div>
  <div id="grid" style="height: 380px"></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('limit').addEventListener('change', (event) => actions.limit(api, event.target.value));
document.getElementById('clear').addEventListener('click', () => actions.clear(api));
example.js
const names = ['Alex', 'Blair', 'Casey', 'Drew', 'Emery', 'Finn', 'Gray', 'Harper'];
export const options = {
  columns: [
    { id: 'name', title: 'Name', width: 120 },
    {
      id: 'score',
      title: 'Score',
      kind: 'number',
      width: 90,
      editable: true,
      sortable: true,
    },
    { id: 'note', title: 'Note', width: 140 },
  ],
  rows: names.map((name, i) => ({ id: i + 1, name, score: 40 + ((i * 13) % 60), note: '' })),
  rowKey: 'id',
};
let say = () => { };
let limit = 70;
/** Style only the score cells at or above the limit: one setCellStyles call, so one redraw. */
function paint(api) {
  const entries = api.getRows().map((row) => ({
    rowKey: row.id,
    columnId: 'score',
    style: row.score >= limit
      ? {
        className: 'high',
        style: { backgroundColor: '#d3f9d8', color: '#0b6b2f', fontWeight: 700 },
      }
      : null,
  }));
  api.setCellStyles(entries);
  return entries.filter((e) => e.style !== null).length;
}
export function setup(api, log) {
  say = log;
  paint(api);
  // When a score is edited, only that row is judged again.
  const off = api.on('editCommitted', ({ rowKey }) => {
    const row = api.getRowByKey(rowKey);
    if (row)
      api.setCellStyle(rowKey, 'score', row.score >= limit
        ? {
          className: 'high',
          style: { backgroundColor: '#d3f9d8', color: '#0b6b2f', fontWeight: 700 },
        }
        : null);
  });
  return () => {
    off();
  };
}
export const actions = {
  limit: (api, value) => {
    limit = Number(value) || 70;
    const count = paint(api);
    say(`Styled ${count} cells at ${limit} or more`);
  },
  clear: (api) => {
    api.clearCellStyles({ columnIds: ['score'] });
    say('Cleared the score styles');
  },
};