Data Grid - 스타일링
Data Grid - 스타일링 (Styling)
그리드 CSS는 쉽게 덮어쓸 수 있습니다.
본문
sx prop 사용하기 (Using the sx prop)
일회성 스타일에는 sx prop을 사용할 수 있어요. 이를 통해 Data Grid 요소에 간단하고 복잡한 커스터마이즈를 모두 직접 적용할 수 있습니다. 허용되는 키는 모든 CSS 속성뿐 아니라 MUI가 제공하는 커스텀 속성입니다. 자세한 내용은 sx prop 페이지를 참고하세요.
<DataGrid sx={{ m: 2 }} /> // Sets the margin to 2 times the spacing unit = 16px
import Box from '@mui/material/Box';
import { DataGrid } from '@mui/x-data-grid';
import { useDemoData } from '@mui/x-data-grid-generator';
export default function SxProp() {
const { data } = useDemoData({
dataSet: 'Commodity',
rowLength: 20,
maxColumns: 5,
});
return (
<Box sx={{ height: 300, width: '100%' }}>
<DataGrid
{...data}
sx={{
boxShadow: 2,
border: 2,
borderColor: 'primary.light',
'& .MuiDataGrid-cell:hover': {
color: 'primary.main',
},
}}
/>
</Box>
);
}
컬럼 헤더 스타일링 (Styling column headers)
GridColDef 타입에는 헤더에 클래스 이름과 커스텀 CSS를 적용하는 속성이 있습니다.
headerClassName: 컬럼 헤더에 클래스 이름을 적용합니다.GridColumnHeaderParams객체로 호출되는 함수일 수도 있어요.headerAlign: 헤더의 콘텐츠를 정렬합니다. 'left' | 'right' | 'center'여야 합니다.
const columns: GridColDef[] = [
{
field: 'first',
headerClassName: 'super-app-theme--header',
headerAlign: 'center',
},
{
field: 'last',
headerClassName: 'super-app-theme--header',
headerAlign: 'center',
},
];
import Box from '@mui/material/Box';
import { GridColDef, DataGrid } from '@mui/x-data-grid';
const columns: GridColDef[] = [
{
field: 'first',
rowHeader: true,
headerClassName: 'super-app-theme--header',
headerAlign: 'center',
width: 140,
},
{
field: 'last',
rowHeader: true,
headerClassName: 'super-app-theme--header',
headerAlign: 'center',
width: 140,
},
];
const rows = [
{
id: 1,
first: 'Jane',
last: 'Carter',
},
{
id: 2,
first: 'Jack',
last: 'Smith',
},
{
id: 3,
first: 'Gill',
last: 'Martin',
},
];
export default function StylingHeaderGrid() {
return (
<Box
sx={{
height: 300,
width: '100%',
'& .super-app-theme--header': {
backgroundColor: 'rgba(255, 7, 0, 0.55)',
},
}}
>
<DataGrid rows={rows} columns={columns} />
</Box>
);
}
행 스타일링 (Styling rows)
getRowClassName prop은 각 행에 커스텀 CSS 클래스를 적용하는 데 사용할 수 있어요. GridRowParams 객체로 호출되며 문자열을 반환해야 합니다. 때로는 더 높은 특이성(specificity)의 CSS 선택자로 기존 규칙을 재정의해야 할 수도 있습니다.
interface GridRowParams<R extends GridRowModel = GridRowModel> {
/**
* The grid row id.
*/
id: GridRowId;
/**
* The row model of the row that the current cell belongs to.
*/
row: R;
/**
* All grid columns.
*/
columns: GridColDef[];
}
import Box from '@mui/material/Box';
import { DataGrid } from '@mui/x-data-grid';
import { useDemoData } from '@mui/x-data-grid-generator';
import { darken, lighten, styled, Theme } from '@mui/material/styles';
const getBackgroundColor = (color: string, theme: Theme, coefficient: number) => ({
backgroundColor: darken(color, coefficient),
...theme.applyStyles('light', {
backgroundColor: lighten(color, coefficient),
}),
});
const StyledDataGrid = styled(DataGrid)(({ theme }) => ({
'& .super-app-theme--Open': {
...getBackgroundColor(theme.palette.info.main, theme, 0.7),
'&:hover': {
...getBackgroundColor(theme.palette.info.main, theme, 0.6),
},
'&.Mui-selected': {
...getBackgroundColor(theme.palette.info.main, theme, 0.5),
'&:hover': {
...getBackgroundColor(theme.palette.info.main, theme, 0.4),
},
},
},
'& .super-app-theme--Filled': {
...getBackgroundColor(theme.palette.success.main, theme, 0.7),
'&:hover': {
...getBackgroundColor(theme.palette.success.main, theme, 0.6),
},
'&.Mui-selected': {
...getBackgroundColor(theme.palette.success.main, theme, 0.5),
'&:hover': {
...getBackgroundColor(theme.palette.success.main, theme, 0.4),
},
},
},
'& .super-app-theme--PartiallyFilled': {
...getBackgroundColor(theme.palette.warning.main, theme, 0.7),
'&:hover': {
...getBackgroundColor(theme.palette.warning.main, theme, 0.6),
},
'&.Mui-selected': {
...getBackgroundColor(theme.palette.warning.main, theme, 0.5),
'&:hover': {
...getBackgroundColor(theme.palette.warning.main, theme, 0.4),
},
},
},
'& .super-app-theme--Rejected': {
...getBackgroundColor(theme.palette.error.main, theme, 0.7),
'&:hover': {
...getBackgroundColor(theme.palette.error.main, theme, 0.6),
},
'&.Mui-selected': {
...getBackgroundColor(theme.palette.error.main, theme, 0.5),
'&:hover': {
...getBackgroundColor(theme.palette.error.main, theme, 0.4),
},
},
},
}));
export default function StylingRowsGrid() {
const { data, loading } = useDemoData({
dataSet: 'Commodity',
rowLength: 100,
});
return (
<Box sx={{ height: 400, width: '100%' }}>
<StyledDataGrid
{...data}
loading={loading}
getRowClassName={(params) => `super-app-theme--${params.row.status}`}
/>
</Box>
);
}
셀 스타일링 (Styling cells)
셀에 커스텀 CSS 클래스를 적용하는 방법은 여러 가지가 있습니다.
GridColDef의cellClassName속성 사용하기:
이 속성은 정의된 컬럼의 모든 셀에 적용되는 CSS 클래스를 설정하게 해줍니다. GridCellParams 객체로 호출되는 함수일 수도 있어요.
const columns: GridColDef[] = [
{
field: 'name',
cellClassName: 'super-app-theme--cell',
},
{
field: 'score',
type: 'number',
cellClassName: (params: GridCellParams<number>) =>
clsx('super-app', {
negative: params.value < 0,
positive: params.value > 0,
}),
},
];
import Box from '@mui/material/Box';
import clsx from 'clsx';
import { GridColDef, DataGrid, GridCellParams } from '@mui/x-data-grid';
const columns: GridColDef[] = [
{
field: 'name',
rowHeader: true,
cellClassName: 'super-app-theme--cell',
},
{
field: 'score',
type: 'number',
width: 140,
cellClassName: (params: GridCellParams<any, number>) => {
if (params.value == null) {
return '';
}
return clsx('super-app', {
negative: params.value < 0,
positive: params.value > 0,
});
},
},
];
const rows = [
{
id: 1,
name: 'Jane',
score: 100,
},
{
id: 2,
name: 'Jack',
score: -100,
},
{
id: 3,
name: 'Gill',
score: -50,
},
];
export default function StylingCellsGrid() {
return (
<Box
sx={{
height: 300,
width: '100%',
'& .super-app-theme--cell': {
backgroundColor: 'rgba(224, 183, 60, 0.55)',
color: '#1a3e72',
fontWeight: '600',
},
'& .super-app.negative': {
backgroundColor: 'rgba(157, 255, 118, 0.49)',
color: '#1a3e72',
fontWeight: '600',
},
'& .super-app.positive': {
backgroundColor: '#d47483',
color: '#1a3e72',
fontWeight: '600',
},
}}
>
<DataGrid rows={rows} columns={columns} />
</Box>
);
}
getCellClassNameprop 사용하기:
이 prop은 모든 컬럼의 모든 셀에 대해 호출됩니다. 첫 번째 옵션과 달리 이 prop은 컬럼 수준이 아니라 Data Grid 수준에서 정의됩니다. GridCellParams 객체로도 호출됩니다.
import Box from '@mui/material/Box';
import { GridColDef, DataGrid, GridCellParams, gridClasses } from '@mui/x-data-grid';
const columns: GridColDef[] = [
{ field: 'city', rowHeader: true },
{ field: 'oct', type: 'number', valueFormatter: (value) => `${value} °C` },
{ field: 'nov', type: 'number', valueFormatter: (value) => `${value} °C` },
{ field: 'dec', type: 'number', valueFormatter: (value) => `${value} °C` },
];
const rows = [
{ id: 1, city: 'Amsterdam', oct: 7.1, nov: 4, dec: 10.2 },
{ id: 2, city: 'Barcelona', oct: 14.9, nov: 12.3, dec: 18.2 },
{ id: 3, city: 'Paris', oct: 8.1, nov: 5.4, dec: 12.3 },
{ id: 4, city: 'São Paulo', oct: 20.2, nov: 21.1, dec: 19.2 },
];
export default function StylingAllCells() {
return (
<Box
sx={{
height: 300,
width: '100%',
[`.${gridClasses.cell}.cold`]: {
backgroundColor: '#b9d5ff91',
color: '#1a3e72',
},
[`.${gridClasses.cell}.hot`]: {
backgroundColor: '#ff943975',
color: '#1a3e72',
},
}}
>
<DataGrid
rows={rows}
columns={columns}
getCellClassName={(params: GridCellParams<any, any, number>) => {
if (params.field === 'city' || params.value == null) {
return '';
}
return params.value >= 15 ? 'hot' : 'cold';
}}
/>
</Box>
);
}
셀 정렬 (Cell alignment)
GridColDef의 align 속성을 사용해 셀 콘텐츠의 정렬을 바꿀 수 있어요. 다음 값 중 하나를 선택하세요: 'left' | 'right' | 'center'.
:::warning
헤더 콘텐츠를 정렬하려면 headerAlign을 사용해야 합니다.
:::
줄무늬 행 (Striped rows)
getRowClassName에 전달되는 indexRelativeToCurrentPage 매개변수를 사용해 행에 번갈아 스타일을 적용할 수 있어요.
다음 데모는 어떻게 할 수 있는지 보여줍니다.
import { alpha, styled } from '@mui/material/styles';
import { DataGrid, gridClasses } from '@mui/x-data-grid';
import { useDemoData } from '@mui/x-data-grid-generator';
const ODD_OPACITY = 0.2;
const StripedDataGrid = styled(DataGrid)(({ theme }) => ({
[`& .${gridClasses.row}.even`]: {
backgroundColor: theme.palette.grey[200],
'&:hover': {
backgroundColor: alpha(theme.palette.primary.main, ODD_OPACITY),
'@media (hover: none)': {
backgroundColor: 'transparent',
},
},
'&.Mui-selected': {
backgroundColor: alpha(
theme.palette.primary.main,
ODD_OPACITY + theme.palette.action.selectedOpacity,
),
'&:hover': {
backgroundColor: alpha(
theme.palette.primary.main,
ODD_OPACITY +
theme.palette.action.selectedOpacity +
theme.palette.action.hoverOpacity,
),
// Reset on touch devices, it doesn't add specificity
'@media (hover: none)': {
backgroundColor: alpha(
theme.palette.primary.main,
ODD_OPACITY + theme.palette.action.selectedOpacity,
),
},
},
},
...theme.applyStyles('dark', {
backgroundColor: theme.palette.grey[800],
}),
},
}));
export default function StripedGrid() {
const { data, loading } = useDemoData({
dataSet: 'Employee',
rowLength: 200,
});
return (
<div style={{ height: 400, width: '100%' }}>
<StripedDataGrid
loading={loading}
{...data}
getRowClassName={(params) =>
params.indexRelativeToCurrentPage % 2 === 0 ? 'even' : 'odd'
}
/>
</div>
);
}
컨테이너, 헤더, 고정 섹션 (Container, header, and pinned sections)
기본적으로 Data Grid는 그리드 컨테이너, 컬럼 헤더, 고정된 행과 컬럼의 배경색에 Material UI theme.palette.background.default 색상을 사용합니다.
이 배경색은 다음 테마 구성으로 재정의할 수 있어요.
import { createTheme } from '@mui/material/styles';
import type {} from '@mui/x-data-grid/themeAugmentation';
const theme = createTheme({
palette: {
DataGrid: {
// Container background
bg: '#f8fafc',
// Pinned rows and columns background
pinnedBg: '#f1f5f9',
// Column header background
headerBg: '#eaeff5',
},
},
});
Material UI v6에서 라이트/다크 모드 (Light and dark mode in Material UI v6)
Material UI v6 사용자는 colorSchemes 속성을 사용해 라이트/다크 모드에 서로 다른 색상을 지정할 수 있어요.
import { createTheme } from '@mui/material/styles';
import type {} from '@mui/x-data-grid/themeAugmentation';
const theme = createTheme({
colorSchemes: {
light: {
palette: {
DataGrid: {
bg: '#f8fafc',
pinnedBg: '#f1f5f9',
headerBg: '#eaeff5',
},
},
},
dark: {
palette: {
DataGrid: {
bg: '#334155',
pinnedBg: '#293548',
headerBg: '#1e293b',
},
},
},
},
});
Material UI v5에서 라이트/다크 모드 (Light and dark mode in Material UI v5)
Material UI v5는 두 개의 서로 다른 테마로 라이트/다크 모드에 서로 다른 색상을 지정하는 것을 지원합니다. 아래 데모에서 확인할 수 있어요.
import * as React from 'react';
import { ThemeProvider, createTheme } from '@mui/material/styles';
import { GridColDef } from '@mui/x-data-grid';
import { DataGridPremium } from '@mui/x-data-grid-premium';
import Stack from '@mui/material/Stack';
import ToggleButtonGroup from '@mui/material/ToggleButtonGroup';
import ToggleButton from '@mui/material/ToggleButton';
import DarkModeIcon from '@mui/icons-material/DarkMode';
import LightModeIcon from '@mui/icons-material/LightMode';
type PaletteMode = 'light' | 'dark';
const getTheme = (mode: PaletteMode) =>
createTheme({
palette: {
mode,
DataGrid: {
bg: mode === 'light' ? '#f8fafc' : '#334155',
pinnedBg: mode === 'light' ? '#f1f5f9' : '#293548',
headerBg: mode === 'light' ? '#eaeff5' : '#1e293b',
},
},
});
const columns: GridColDef<(typeof rows)[number]>[] = [
{ field: 'id', headerName: 'ID', width: 90 },
{
field: 'firstName',
headerName: 'First name',
width: 150,
editable: true,
},
{
field: 'lastName',
headerName: 'Last name',
width: 150,
editable: true,
},
{
field: 'age',
headerName: 'Age',
type: 'number',
width: 110,
editable: true,
},
{
field: 'fullName',
headerName: 'Full name',
rowHeader: true,
description: 'This column has a value getter and is not sortable.',
sortable: false,
width: 160,
valueGetter: (value, row) => `${row.firstName || ''} ${row.lastName || ''}`,
},
];
const rows = [
{ id: 1, lastName: 'Snow', firstName: 'Jon', age: 14 },
{ id: 2, lastName: 'Lannister', firstName: 'Cersei', age: 31 },
{ id: 3, lastName: 'Lannister', firstName: 'Jaime', age: 31 },
{ id: 4, lastName: 'Stark', firstName: 'Arya', age: 11 },
{ id: 5, lastName: 'Targaryen', firstName: 'Daenerys', age: null },
{ id: 6, lastName: 'Melisandre', firstName: null, age: 150 },
{ id: 7, lastName: 'Clifford', firstName: 'Ferrara', age: 44 },
{ id: 8, lastName: 'Frances', firstName: 'Rossini', age: 36 },
{ id: 9, lastName: 'Roxie', firstName: 'Harvey', age: 65 },
];
export default function BackgroundColorsGrid() {
const [mode, setMode] = React.useState<PaletteMode>('light');
const theme = React.useMemo(() => getTheme(mode), [mode]);
return (
<Stack direction="column" style={{ width: '100%', height: 400 }} sx={{ gap: 1 }}>
<ToggleButtonGroup
size="small"
color="primary"
value={mode}
onChange={(event, value) => setMode(value === null ? mode : value)}
exclusive
>
<ToggleButton value="light" aria-label="Light mode" sx={{ gap: 1 }}>
<LightModeIcon fontSize="small" /> Light
</ToggleButton>
<ToggleButton value="dark" aria-label="Dark mode" sx={{ gap: 1 }}>
<DarkModeIcon fontSize="small" /> Dark
</ToggleButton>
</ToggleButtonGroup>
<ThemeProvider theme={theme}>
<DataGridPremium
rows={rows}
columns={columns}
initialState={{
pagination: {
paginationModel: {
pageSize: 5,
},
},
pinnedColumns: {
left: ['id'],
},
}}
pinnedRows={{
bottom: [rows[0]],
}}
/>
</ThemeProvider>
</Stack>
);
}
커스텀 테마 (Custom theme)
다음 데모는 Ant Design 명세에 맞추기 위해 CSS 커스터마이즈 API를 활용합니다.
import * as React from 'react';
import {
DataGrid,
gridPageCountSelector,
gridPageSelector,
useGridApiContext,
useGridSelector,
} from '@mui/x-data-grid';
import { useDemoData } from '@mui/x-data-grid-generator';
import { Theme, styled } from '@mui/material/styles';
import Pagination from '@mui/material/Pagination';
import PaginationItem from '@mui/material/PaginationItem';
function customCheckbox(theme: Theme) {
return {
'& .MuiCheckbox-root svg': {
width: 16,
height: 16,
backgroundColor: 'transparent',
border: '1px solid #d9d9d9',
borderRadius: 2,
...theme.applyStyles('dark', {
borderColor: 'rgb(67, 67, 67)',
}),
},
'& .MuiCheckbox-root svg path': {
display: 'none',
},
'& .MuiCheckbox-root.Mui-checked:not(.MuiCheckbox-indeterminate) svg': {
backgroundColor: '#1890ff',
borderColor: '#1890ff',
},
'& .MuiCheckbox-root.Mui-checked .MuiIconButton-label:after': {
position: 'absolute',
display: 'table',
border: '2px solid #fff',
borderTop: 0,
borderLeft: 0,
transform: 'rotate(45deg) translate(-50%,-50%)',
opacity: 1,
transition: 'all .2s cubic-bezier(.12,.4,.29,1.46) .1s',
content: '""',
top: '50%',
left: '39%',
width: 5.71428571,
height: 9.14285714,
},
'& .MuiCheckbox-root.MuiCheckbox-indeterminate .MuiIconButton-label:after': {
width: 8,
height: 8,
backgroundColor: '#1890ff',
transform: 'none',
top: '39%',
border: 0,
},
};
}
const StyledDataGrid = styled(DataGrid)(({ theme }) => ({
border: 0,
color: 'rgba(255,255,255,0.85)',
fontFamily: [
'-apple-system',
'BlinkMacSystemFont',
'"Segoe UI"',
'Roboto',
'"Helvetica Neue"',
'Arial',
'sans-serif',
'"Apple Color Emoji"',
'"Segoe UI Emoji"',
'"Segoe UI Symbol"',
].join(','),
WebkitFontSmoothing: 'auto',
letterSpacing: 'normal',
'& .MuiDataGrid-columnsContainer': {
backgroundColor: '#1d1d1d',
...theme.applyStyles('light', {
backgroundColor: '#fafafa',
}),
},
'& .MuiDataGrid-iconSeparator': {
display: 'none',
},
'& .MuiDataGrid-columnHeader, .MuiDataGrid-cell': {
borderRight: '1px solid #303030',
...theme.applyStyles('light', {
borderRightColor: '#f0f0f0',
}),
},
'& .MuiDataGrid-columnsContainer, .MuiDataGrid-cell': {
borderBottom: '1px solid #303030',
...theme.applyStyles('light', {
borderBottomColor: '#f0f0f0',
}),
},
'& .MuiDataGrid-cell': {
color: 'rgba(255,255,255,0.65)',
...theme.applyStyles('light', {
color: 'rgba(0,0,0,.85)',
}),
},
'& .MuiPaginationItem-root': {
borderRadius: 0,
},
...customCheckbox(theme),
...theme.applyStyles('light', {
color: 'rgba(0,0,0,.85)',
}),
}));
function CustomPagination() {
const apiRef = useGridApiContext();
const page = useGridSelector(apiRef, gridPageSelector);
const pageCount = useGridSelector(apiRef, gridPageCountSelector);
return (
<Pagination
color="primary"
variant="outlined"
shape="rounded"
page={page + 1}
count={pageCount}
// @ts-expect-error
renderItem={(props2) => <PaginationItem {...props2} disableRipple />}
onChange={(event: React.ChangeEvent<unknown>, value: number) =>
apiRef.current.setPage(value - 1)
}
/>
);
}
const PAGE_SIZE = 5;
export default function AntDesignGrid() {
const { data } = useDemoData({
dataSet: 'Commodity',
rowLength: 10,
maxColumns: 10,
});
const [paginationModel, setPaginationModel] = React.useState({
pageSize: PAGE_SIZE,
page: 0,
});
return (
<div style={{ height: 400, width: '100%' }}>
<StyledDataGrid
checkboxSelection
paginationModel={paginationModel}
onPaginationModelChange={setPaginationModel}
pageSizeOptions={[PAGE_SIZE]}
slots={{
pagination: CustomPagination,
}}
{...data}
/>
</div>
);
}
행 그룹 스타일링 (Styling row groups)
getRowClassName을 사용해 행 그룹에 커스텀 클래스를 추가한 다음 CSS로 스타일링하세요.
아래 예시는 자식 행 중 하나에 특정 값보다 큰 "Gross" 값이 있을 때 행 그룹을 스타일링하는 방법을 보여줍니다. 이 조건은 gridRowNodeSelector와 gridRowSelector를 사용해 대상 행 타입을 확인하고 행 데이터를 각각 가져옵니다.
import * as React from 'react';
import {
DataGridPremium,
useGridApiRef,
useKeepGroupedColumnsHidden,
GridRowClassNameParams,
gridRowNodeSelector,
gridRowSelector,
} from '@mui/x-data-grid-premium';
import { useMovieData } from '@mui/x-data-grid-generator';
type Movie = ReturnType<typeof useMovieData>['rows'][number];
const EXPECTED_GROSS = 2000000000;
const ROW_HEIGHT = 52;
export default function RowGroupingStyling() {
const apiRef = useGridApiRef();
const data = useMovieData();
const getRowClassName = React.useCallback(
(params: GridRowClassNameParams<Movie>) => {
const node = gridRowNodeSelector(apiRef, params.id);
if (!node) {
return '';
}
if (node.type === 'group') {
for (const childId of node.children) {
const childNode = gridRowNodeSelector(apiRef, childId);
if (childNode && childNode.type === 'leaf') {
const childRow = gridRowSelector(apiRef, childId) as Movie;
if (childRow?.gross && childRow.gross > EXPECTED_GROSS) {
return 'highlighted-group';
}
}
}
return '';
}
const row = params.row;
if (row.gross > EXPECTED_GROSS) {
return 'highlighted-child';
}
return '';
},
[apiRef],
);
const initialState = useKeepGroupedColumnsHidden({
apiRef,
initialState: {
rowGrouping: {
model: ['company'],
},
},
});
return (
<div style={{ height: 400, width: '100%' }}>
<DataGridPremium
{...data}
apiRef={apiRef}
initialState={initialState}
getRowClassName={getRowClassName}
sx={(theme) => ({
'& .highlighted-group': {
'&::before': {
content: '""',
display: 'block',
position: 'absolute',
left: 0,
width: 4,
height: `calc(${ROW_HEIGHT}px * 0.8)`,
marginTop: `calc(${ROW_HEIGHT}px * 0.1)`,
backgroundColor: 'success.main',
borderTopRightRadius: 4,
borderBottomRightRadius: 4,
},
},
'& .highlighted-child': {
backgroundColor: `color-mix(in srgb, ${(theme.vars || theme).palette.success.main} 8%, transparent)`,
'&:hover': {
backgroundColor: `color-mix(in srgb, ${(theme.vars || theme).palette.success.main} 12%, transparent)`,
},
},
})}
/>
</div>
);
}
:::success
스타일링 방법은 sx prop에만 국한되지 않아요. 일반 CSS 파일이나 CSS 모듈 같은 다른 스타일링 솔루션을 사용할 수 있습니다.
:::