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

조건에 맞는 행과 칸에 색 입히기Style rows and cells by a rule

지역이 서울인 행, 상품이 노트북인 칸, 금액이 100만 원 넘는 칸처럼 조건에 맞는 곳에만 스타일을 입혀요. 조건에 맞으면 스타일 이름만 돌려주고, 색은 CSS가 정해요.Style whole rows or single cells that match a rule, such as a region, a product or a large amount. Return only a style name for matches and CSS decides the look.

입문Beginner
직접 써 보기Live preview조건에 맞는 행과 칸에 색 입히기Style rows and cells by 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="region">
      <option value="seoul" selected>서울</option>
      <option value="busan">부산</option>
      <option value="jeju">제주</option>
      <option value="none">강조 안 함</option>
    </select>
    <select aria-label="강조할 상품(칸)" id="product">
      <option value="laptop" selected>노트북</option>
      <option value="monitor">모니터</option>
      <option value="webcam">웹캠</option>
      <option value="none">강조 안 함</option>
    </select>
    <select aria-label="100만 원 이상 금액" id="amount">
      <option value="on" selected>눈에 띄게</option>
      <option value="off">그대로</option>
    </select>
    <button type="button" id="boost">부산 행 금액 높이기</button>
  </div>
  <div id="grid" style="height: 420px"></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);
document.getElementById('region').addEventListener('change', (event) => actions.region(api, event.target.value));
document.getElementById('product').addEventListener('change', (event) => actions.product(api, event.target.value));
document.getElementById('amount').addEventListener('change', (event) => actions.amount(api, event.target.value));
document.getElementById('boost').addEventListener('click', () => actions.boost(api));
example.js
const regions = ['서울', '부산', '대구', '제주'];
const customers = ['한빛물류', '푸른하늘식품', '북극성무역', '다온상사', '새벽농원', '모아패션'];
const products = ['노트북', '모니터', '무선 키보드', '웹캠', '도킹 스테이션'];
const statuses = ['결제 완료', '배송 중', '배송 완료', '취소'];
// 지금 어떤 기준으로 강조할지는 이 변수 세 개가 정해요. 버튼은 값을 바꾸고 api.refresh()로 다시 그려요.
let highlightRegion = '서울';
let highlightProduct = '노트북';
let bigAmount = 'on';
// rowClass는 행 전체, cellClass는 칸 하나에 CSS 클래스 이름을 붙여요. 색은 아래 CSS에서 정해요.
// 둘 다 화면을 그릴 때마다 불려서, 데이터가 바뀌거나 기준이 바뀌면 스타일도 따라가요.
export const options = {
  columns: [
    { id: 'region', title: '지역', width: 80 },
    { id: 'customer', title: '고객사', width: 130 },
    {
      id: 'product',
      title: '상품',
      width: 140,
      cellClass: (ctx) => highlightProduct !== '없음' && ctx.value === highlightProduct ? 'st-product' : undefined,
    },
    { id: 'quantity', title: '수량', kind: 'number', width: 80, align: 'end' },
    {
      id: 'amount',
      title: '금액(원)',
      kind: 'number',
      width: 120,
      align: 'end',
      formatValue: (value) => Number(value).toLocaleString('ko-KR'),
      cellClass: (ctx) => bigAmount === 'on' && Number(ctx.value) >= 1000000 ? 'st-big' : undefined,
    },
    {
      id: 'status',
      title: '상태',
      width: 110,
      cellClass: (ctx) => (ctx.value === '취소' ? 'st-cancel' : undefined),
    },
  ],
  rows: Array.from({ length: 14 }, (_, i) => ({
    id: i + 1,
    region: regions[(i * 3) % 4],
    customer: customers[i % 6],
    product: products[(i * 2) % 5],
    quantity: 1 + ((i * 3) % 9),
    amount: 89000 + ((i * 391000) % 2300000),
    status: statuses[(i * 5) % 4],
  })),
  rowKey: 'id',
  rowClass: (row) => highlightRegion !== '없음' && row.region === highlightRegion ? 'st-region' : undefined,
};
// 스타일 규칙은 예제 안에서 넣었다가, 예제가 끝나면 지워요(접두사 st-로 다른 CSS와 겹치지 않게 해요). 색은 테마 색을 따라가서 밝은 화면과 어두운 화면 모두에서 읽혀요.
const CSS = `
.mxg .mxg-row.st-region { background: color-mix(in srgb, var(--mxg-accent) 14%, var(--mxg-bg)); box-shadow: inset 3px 0 0 var(--mxg-accent); }
.mxg .mxg-cell.st-product { color: var(--mxg-tone-danger-fg); font-weight: 700; }
.mxg .mxg-cell.st-big { background: var(--mxg-bg-dirty); color: var(--mxg-tone-warning-fg); font-weight: 700; }
.mxg .mxg-cell.st-cancel { color: var(--mxg-danger); text-decoration: line-through; }
`;
export function setup(api) {
  highlightRegion = '서울';
  highlightProduct = '노트북';
  bigAmount = 'on';
  const style = document.createElement('style');
  style.textContent = CSS;
  document.head.append(style);
  api.refresh();
  return () => style.remove();
}
// 컨트롤 값은 영문 id(seoul·none 같은)이고, 표의 지역·상품 글자로 바꿔서 써요.
const regionOf = { seoul: '서울', busan: '부산', jeju: '제주' };
const productOf = { laptop: '노트북', monitor: '모니터', webcam: '웹캠' };
export const actions = {
  region: (api, value) => {
    highlightRegion = regionOf[value ?? 'none'] ?? '없음';
    api.refresh();
  },
  product: (api, value) => {
    highlightProduct = productOf[value ?? 'none'] ?? '없음';
    api.refresh();
  },
  amount: (api, value) => {
    bigAmount = value ?? 'off';
    api.refresh();
  },
  // 데이터가 바뀌면 스타일도 바로 따라와요: 100만 원이 안 되는 부산 행 하나를 240만 원으로 바꿔요.
  boost: (api) => {
    const row = api.getRows().find((r) => r.region === '부산' && r.amount < 1000000);
    if (row)
      api.updateRows([{ ...row, amount: 2400000 }]);
  },
};

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="Row highlight: region" id="region">
      <option value="seoul" selected>Seoul</option>
      <option value="busan">Busan</option>
      <option value="jeju">Jeju</option>
      <option value="none">None</option>
    </select>
    <select aria-label="Cell highlight: product" id="product">
      <option value="laptop" selected>Laptop</option>
      <option value="monitor">Monitor</option>
      <option value="webcam">Webcam</option>
      <option value="none">None</option>
    </select>
    <select aria-label="Amounts over $1K" id="amount">
      <option value="on" selected>Highlight</option>
      <option value="off">Plain</option>
    </select>
    <button type="button" id="boost">Boost a Busan amount</button>
  </div>
  <div id="grid" style="height: 420px"></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);
document.getElementById('region').addEventListener('change', (event) => actions.region(api, event.target.value));
document.getElementById('product').addEventListener('change', (event) => actions.product(api, event.target.value));
document.getElementById('amount').addEventListener('change', (event) => actions.amount(api, event.target.value));
document.getElementById('boost').addEventListener('click', () => actions.boost(api));
example.js
const regions = ['Seoul', 'Busan', 'Daegu', 'Jeju'];
const customers = [
  'Northwind Logistics',
  'Bluesky Foods',
  'Polaris Trading',
  'Dawn Commerce',
  'Sunrise Farm',
  'Moda Fashion',
];
const products = ['Laptop', 'Monitor', 'Wireless Keyboard', 'Webcam', 'Docking Station'];
const statuses = ['Paid', 'Shipping', 'Delivered', 'Cancelled'];
// Control values are English ids (seoul, laptop, none ...); they are mapped to the values in the data.
const NONE = 'none';
const REGION = { seoul: 'Seoul', busan: 'Busan', jeju: 'Jeju' };
const PRODUCT = { laptop: 'Laptop', monitor: 'Monitor', webcam: 'Webcam' };
const toRegion = (value) => REGION[value ?? NONE] ?? NONE;
const toProduct = (value) => PRODUCT[value ?? NONE] ?? NONE;
// These three variables decide what is highlighted now. A button changes the value and redraws with api.refresh().
let highlightRegion = 'Seoul';
let highlightProduct = 'Laptop';
let bigAmount = 'on';
// rowClass attaches a CSS class name to a whole row, cellClass to a single cell. The colors are set in the CSS below.
// Both are called each time the screen is drawn, so the styles follow when the data or the rule changes.
export const options = {
  columns: [
    { id: 'region', title: 'Region', width: 80 },
    { id: 'customer', title: 'Customer', width: 150 },
    {
      id: 'product',
      title: 'Product',
      width: 160,
      cellClass: (ctx) => highlightProduct !== NONE && ctx.value === highlightProduct ? 'st-product' : undefined,
    },
    { id: 'quantity', title: 'Qty', kind: 'number', width: 80, align: 'end' },
    {
      id: 'amount',
      title: 'Amount ($)',
      kind: 'number',
      width: 120,
      align: 'end',
      formatValue: (value) => Number(value).toLocaleString('en-US'),
      cellClass: (ctx) => (bigAmount === 'on' && Number(ctx.value) >= 1000 ? 'st-big' : undefined),
    },
    {
      id: 'status',
      title: 'Status',
      width: 110,
      cellClass: (ctx) => (ctx.value === 'Cancelled' ? 'st-cancel' : undefined),
    },
  ],
  rows: Array.from({ length: 14 }, (_, i) => ({
    id: i + 1,
    region: regions[(i * 3) % 4],
    customer: customers[i % 6],
    product: products[(i * 2) % 5],
    quantity: 1 + ((i * 3) % 9),
    amount: 89 + ((i * 391) % 2300),
    status: statuses[(i * 5) % 4],
  })),
  rowKey: 'id',
  rowClass: (row) => highlightRegion !== NONE && row.region === highlightRegion ? 'st-region' : undefined,
};
// The style rules are added inside the example and removed when it ends (the st- prefix keeps them from clashing with other CSS). Colors follow the theme, so they read on both light and dark screens.
const CSS = `
.mxg .mxg-row.st-region { background: color-mix(in srgb, var(--mxg-accent) 14%, var(--mxg-bg)); box-shadow: inset 3px 0 0 var(--mxg-accent); }
.mxg .mxg-cell.st-product { color: var(--mxg-tone-danger-fg); font-weight: 700; }
.mxg .mxg-cell.st-big { background: var(--mxg-bg-dirty); color: var(--mxg-tone-warning-fg); font-weight: 700; }
.mxg .mxg-cell.st-cancel { color: var(--mxg-danger); text-decoration: line-through; }
`;
export function setup(api) {
  highlightRegion = 'Seoul';
  highlightProduct = 'Laptop';
  bigAmount = 'on';
  const style = document.createElement('style');
  style.textContent = CSS;
  document.head.append(style);
  api.refresh();
  return () => style.remove();
}
export const actions = {
  region: (api, value) => {
    highlightRegion = toRegion(value);
    api.refresh();
  },
  product: (api, value) => {
    highlightProduct = toProduct(value);
    api.refresh();
  },
  amount: (api, value) => {
    bigAmount = value ?? 'off';
    api.refresh();
  },
  // When the data changes, the style follows at once: change one Busan row under $1,000 to $2,400.
  boost: (api) => {
    const row = api.getRows().find((r) => r.region === 'Busan' && r.amount < 1000);
    if (row)
      api.updateRows([{ ...row, amount: 2400 }]);
  },
};