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

별점: 보기만 하는 별과 눌러서 바꾸는 별Ratings: read-only stars and clickable stars

내장 별점으로 평점을 보여 주고, 직접 만든 칸으로 별을 눌러 내 평점을 바꿔요. 같은 별을 다시 누르면 지워져요.Show ratings with the built-in stars and let people change their own rating by clicking stars in a custom cell. Clicking the same star again clears it.

활용Intermediate
직접 써 보기Live preview별점: 보기만 하는 별과 눌러서 바꾸는 별Ratings: read-only stars and clickable stars

코드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="clear">내 평점 모두 지우기</button>
  </div>
  <div id="grid" style="height: 260px"></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('clear').addEventListener('click', () => actions.clear(api));
example.js
// 예제 틀이 알려 주는 페이지 언어(ko/en)에 맞는 문구를 골라요.
const L = (ko, en) => document.documentElement.dataset.lang === 'en' ? en : ko;
// 손가락으로 쓰는 화면(폰)인지 알려 줘요. 이런 화면에서는 누를 곳을 40px 이상으로 키워요.
const coarse = () => window.matchMedia('(pointer: coarse), (max-width: 480px)').matches;
// 칸 안의 내용은 기본으로 세로 가운데가 아니에요. .mxg-cell-center 상자에 넣으면 가운데에 와요.
const centered = (el) => {
  const box = document.createElement('div');
  box.className = 'mxg-cell-center';
  el.append(box);
  return box;
};
// 왼쪽 "고객 평점"은 내장 별점이라 보기만 해요(반올림하고 0~별 개수로 맞춰요). "내 평점"은 별을 누르면 바뀌는
// 직접 만든 칸이에요. 별은 버튼이라 Tab으로 이동해 Enter·Space로 고를 수 있고, 별 사이는 좌우 화살표로 옮겨요.
// 그리기만 하고, 누름은 setup에서 한 번만 받아서 값을 바꿔요.
const MAX = 5;
const stars = () => {
  let root;
  let marks = [];
  return {
    mount(el, ctx) {
      root = centered(el);
      root.setAttribute('role', 'radiogroup');
      marks = Array.from({ length: MAX }, (_, i) => {
        const star = document.createElement('button');
        star.type = 'button';
        star.dataset.star = String(i + 1);
        star.setAttribute('role', 'radio');
        const size = coarse() ? 40 : 24;
        star.style.cssText = `cursor: pointer; font: inherit; font-size: 18px; min-width: ${size}px; height: ${size}px; padding: 0; border: 0; background: transparent;`;
        star.addEventListener('keydown', (event) => {
          if (event.key !== 'ArrowRight' && event.key !== 'ArrowLeft')
            return;
          event.preventDefault();
          // 양 끝에서는 더 가지 않고 멈춰요(처음으로 돌아가지 않아요).
          marks[Math.max(0, Math.min(MAX - 1, i + (event.key === 'ArrowRight' ? 1 : -1)))]?.focus();
        });
        root.append(star);
        return star;
      });
      this.update(ctx);
    },
    update(ctx) {
      const value = Math.round(Number(ctx.value) || 0);
      root.setAttribute('aria-label', L(`${ctx.row.product} 내 평점`, `${ctx.row.product} my rating`));
      marks.forEach((star, i) => {
        star.textContent = i < value ? '★' : '☆';
        star.setAttribute('aria-label', L(`별 ${i + 1}개`, `${i + 1} ${i === 0 ? 'star' : 'stars'}`));
        star.setAttribute('aria-checked', String(i + 1 === value));
        // 칸에 들어가면 지금 점수의 별(0점이면 첫 별)에서 시작하도록, 그 별만 Tab으로 닿게 해요.
        star.tabIndex = i === Math.max(0, value - 1) ? 0 : -1;
        star.style.color = i < value ? 'var(--mxg-accent)' : 'var(--mxg-fg-muted)';
      });
    },
    destroy() {
      marks = [];
    },
  };
};
const review = {
  id: 'review',
  title: '고객 평점(보기만)',
  kind: 'number',
  width: 150,
  cellRenderer: 'rating',
};
const mine = {
  id: 'mine',
  title: '내 평점(눌러서 바꾸기)',
  kind: 'number',
  width: coarse() ? 230 : 190,
  cellRenderer: stars,
};
export const options = {
  // 폰에서는 눌러서 바꾸는 칸을 먼저 보여요.
  columns: [
    { id: 'product', title: '상품', width: 150 },
    ...(coarse() ? [mine, review] : [review, mine]),
  ],
  rows: [
    { id: 1, product: '높이 조절 책상', review: 5, mine: 5 },
    { id: 2, product: '메쉬 의자', review: 4, mine: 4 },
    { id: 3, product: '모니터 받침대', review: 3.6, mine: 3 },
    { id: 4, product: '스탠드 조명', review: 2, mine: 2 },
    { id: 5, product: '케이블 정리함', review: null, mine: 0 },
  ],
  rowKey: 'id',
  saveMode: 'none', // 이 예제는 저장 흐름이 아니라서 "저장 안 한 변경" 표시를 쓰지 않아요
  ...(coarse() ? { rowHeight: 44 } : {}),
};
export function setup(api, log) {
  log({
    ko: '고객 평점 3.6은 4개로 반올림해서 그려요. 비어 있으면 아무것도 그리지 않아요.',
    en: 'The customer rating 3.6 is drawn rounded to 4. An empty value draws nothing.',
  });
  return api.on('cellClicked', (e) => {
    const star = e.event.target?.closest('[data-star]');
    if (e.columnId !== 'mine' || !star)
      return;
    const next = Number(star.dataset.star);
    // 지금 점수와 같은 별을 다시 누르면 0점으로 지워요.
    const value = next === e.row.mine ? 0 : next;
    api.updateRows([{ ...e.row, mine: value }]);
    log({ ko: `${e.row.product}: 내 평점 ${value}점`, en: `${e.row.product}: my rating ${value}` });
  });
}
export const actions = {
  clear: (api) => {
    api.updateRows(api.getRows().map((row) => ({ ...row, mine: 0 })));
  },
};

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="clear">Clear all my ratings</button>
  </div>
  <div id="grid" style="height: 260px"></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('clear').addEventListener('click', () => actions.clear(api));
example.js
// Tells whether this is a touch screen (phone). On such screens the tap target grows to at least 40px.
const coarse = () => window.matchMedia('(pointer: coarse), (max-width: 480px)').matches;
// Cell content is not vertically centered by default. Putting it in a .mxg-cell-center box centers it.
const centered = (el) => {
  const box = document.createElement('div');
  box.className = 'mxg-cell-center';
  el.append(box);
  return box;
};
// The left "Customer rating" is the built-in star rating and is read-only (rounded and clamped to 0..star count). "My rating" is
// a custom cell that changes when you click a star. Stars are buttons, so Tab moves to them and Enter/Space picks one; left/right arrows move between stars.
// It only draws; clicks are handled once in setup, which changes the value.
const MAX = 5;
const stars = () => {
  let root;
  let marks = [];
  return {
    mount(el, ctx) {
      root = centered(el);
      root.setAttribute('role', 'radiogroup');
      marks = Array.from({ length: MAX }, (_, i) => {
        const star = document.createElement('button');
        star.type = 'button';
        star.dataset.star = String(i + 1);
        star.setAttribute('role', 'radio');
        const size = coarse() ? 40 : 24;
        star.style.cssText = `cursor: pointer; font: inherit; font-size: 18px; min-width: ${size}px; height: ${size}px; padding: 0; border: 0; background: transparent;`;
        star.addEventListener('keydown', (event) => {
          if (event.key !== 'ArrowRight' && event.key !== 'ArrowLeft')
            return;
          event.preventDefault();
          // Stop at either end instead of wrapping around to the start.
          marks[Math.max(0, Math.min(MAX - 1, i + (event.key === 'ArrowRight' ? 1 : -1)))]?.focus();
        });
        root.append(star);
        return star;
      });
      this.update(ctx);
    },
    update(ctx) {
      const value = Math.round(Number(ctx.value) || 0);
      root.setAttribute('aria-label', `${ctx.row.product} my rating`);
      marks.forEach((star, i) => {
        star.textContent = i < value ? '★' : '☆';
        star.setAttribute('aria-label', `${i + 1} ${i === 0 ? 'star' : 'stars'}`);
        star.setAttribute('aria-checked', String(i + 1 === value));
        // Only the star for the current score (the first star at 0) is reachable by Tab, so entering the cell starts there.
        star.tabIndex = i === Math.max(0, value - 1) ? 0 : -1;
        star.style.color = i < value ? 'var(--mxg-accent)' : 'var(--mxg-fg-muted)';
      });
    },
    destroy() {
      marks = [];
    },
  };
};
const review = {
  id: 'review',
  title: 'Customer rating (read-only)',
  kind: 'number',
  width: 190,
  cellRenderer: 'rating',
};
const mine = {
  id: 'mine',
  title: 'My rating (click to change)',
  kind: 'number',
  width: coarse() ? 240 : 210,
  cellRenderer: stars,
};
export const options = {
  // On a phone, the clickable cell comes first.
  columns: [
    { id: 'product', title: 'Product', width: 150 },
    ...(coarse() ? [mine, review] : [review, mine]),
  ],
  rows: [
    { id: 1, product: 'Height-adjustable desk', review: 5, mine: 5 },
    { id: 2, product: 'Mesh chair', review: 4, mine: 4 },
    { id: 3, product: 'Monitor stand', review: 3.6, mine: 3 },
    { id: 4, product: 'Desk lamp', review: 2, mine: 2 },
    { id: 5, product: 'Cable organizer', review: null, mine: 0 },
  ],
  rowKey: 'id',
  saveMode: 'none', // This example is not a save flow, so it does not use the "unsaved changes" marker
  ...(coarse() ? { rowHeight: 44 } : {}),
};
export function setup(api, log) {
  log('The customer rating 3.6 is drawn rounded to 4. An empty value draws nothing.');
  return api.on('cellClicked', (e) => {
    const star = e.event.target?.closest('[data-star]');
    if (e.columnId !== 'mine' || !star)
      return;
    const next = Number(star.dataset.star);
    // Clicking the star equal to the current score again clears it to 0.
    const value = next === e.row.mine ? 0 : next;
    api.updateRows([{ ...e.row, mine: value }]);
    log(`${e.row.product}: my rating ${value}`);
  });
}
export const actions = {
  clear: (api) => {
    api.updateRows(api.getRows().map((row) => ({ ...row, mine: 0 })));
  },
};