Data Grid - 이벤트
Data Grid - 이벤트 (Events)
Data Grid가 발생시키는 이벤트를 구독해 커스텀 동작을 트리거할 수 있어요.
본문
이벤트 구독하기 (Subscribing to events)
Data Grid에 이벤트 핸들러를 제공해 발생하는 이벤트 중 하나에 구독할 수 있어요.
핸들러는 세 개의 인자로 호출되는 메서드입니다.
- 이벤트와 관련된 정보를 담은 매개변수
- 사용 가능할 때 DOM 이벤트 또는 React 합성 이벤트를 담은
MuiEvent GridApi를 담은GridCallbackDetails— Data Grid Pro나 Data Grid Premium을 사용하는 경우에만
예를 들어, rowClick 이벤트에 대한 핸들러는 다음과 같아요.
const handleEvent: GridEventListener<'rowClick'> = (
params, // GridRowParams
event, // MuiEvent<React.MouseEvent<HTMLElement>>
details, // GridCallbackDetails
) => {
setMessage(`Movie "${params.row.title}" clicked`);
};
이 이벤트 핸들러를 여러 가지 방법으로 Data Grid에 제공할 수 있어요.
이벤트의 prop으로
<DataGrid onRowClick={handleEvent} {...other} />
:::info 모든 이벤트에 전용 prop이 있는 것은 아닙니다. 특정 이벤트에 전용 prop이 있는지 확인하려면 아래 Catalog of events의 예시를 확인하세요. :::
다음 데모는 onRowClick prop으로 rowClick 이벤트를 구독하는 방법을 보여줘요. 아무 행이나 클릭해 보세요.
import * as React from 'react';
import { DataGrid, GridEventListener } from '@mui/x-data-grid';
import { useMovieData } from '@mui/x-data-grid-generator';
import Alert from '@mui/material/Alert';
import Box from '@mui/material/Box';
import Stack from '@mui/material/Stack';
export default function SubscribeToEventsProp() {
const [message, setMessage] = React.useState('');
const data = useMovieData();
const handleRowClick: GridEventListener<'rowClick'> = (params) => {
setMessage(`Movie "${params.row.title}" clicked`);
};
return (
<Stack spacing={2} sx={{ width: '100%' }}>
<Box sx={{ height: 300, width: '100%' }}>
<DataGrid onRowClick={handleRowClick} {...data} />
</Box>
{message && <Alert severity="info">{message}</Alert>}
</Stack>
);
}
useGridEvent로
useGridEvent(apiRef, 'rowClick', handleEvent);
:::warning 이 훅은 Data Grid의 스코프 안에서만 사용할 수 있습니다(즉, 컴포넌트 slot이나 셀 렌더러 안). :::
다음 데모는 useGridEvent()로 rowClick 이벤트를 구독하는 방법을 보여줘요. 아무 행이나 클릭해 보세요.
import * as React from 'react';
import {
DataGrid,
GridEventListener,
GridFooter,
useGridEvent,
useGridApiContext,
} from '@mui/x-data-grid';
import { useMovieData } from '@mui/x-data-grid-generator';
import Alert from '@mui/material/Alert';
import Box from '@mui/material/Box';
import Stack from '@mui/material/Stack';
function Footer() {
const [message, setMessage] = React.useState('');
const apiRef = useGridApiContext();
const handleRowClick: GridEventListener<'rowClick'> = (params) => {
setMessage(`Movie "${params.row.title}" clicked`);
};
useGridEvent(apiRef, 'rowClick', handleRowClick);
return (
<React.Fragment>
<GridFooter />
{message && <Alert severity="info">{message}</Alert>}
</React.Fragment>
);
}
export default function SubscribeToEventsHook() {
const data = useMovieData();
return (
<Stack spacing={2} sx={{ width: '100%' }}>
<Box sx={{ height: 350, width: '100%' }}>
<DataGrid {...data} slots={{ footer: Footer }} />
</Box>
</Stack>
);
}
apiRef.current.subscribeEvent로
apiRef.current.subscribeEvent('rowClick', handleEvent);
다음 데모는 apiRef.current.subscribeEvent로 rowClick 이벤트를 구독하는 방법을 보여줘요. 아무 행이나 클릭해 보세요.
import * as React from 'react';
import { DataGridPro, GridEventListener, useGridApiRef } from '@mui/x-data-grid-pro';
import { useMovieData } from '@mui/x-data-grid-generator';
import Alert from '@mui/material/Alert';
import Stack from '@mui/material/Stack';
import Box from '@mui/material/Box';
export default function SubscribeToEventsApiRef() {
const apiRef = useGridApiRef();
const [message, setMessage] = React.useState('');
const data = useMovieData();
React.useEffect(() => {
const handleRowClick: GridEventListener<'rowClick'> = (params) => {
setMessage(`Movie "${params.row.title}" clicked`);
};
// The `subscribeEvent` method will automatically unsubscribe in the cleanup function of the `useEffect`.
return apiRef.current?.subscribeEvent('rowClick', handleRowClick);
}, [apiRef]);
return (
<Stack spacing={2} sx={{ width: '100%' }}>
<Box sx={{ height: 300, width: '100%' }}>
<DataGridPro apiRef={apiRef} {...data} />
</Box>
{message && <Alert severity="info">{message}</Alert>}
</Stack>
);
}
:::warning
apiRef.current.subscribeEvent 메서드는 호출 시 주어진 핸들러를 구독 해제하는 정리(cleaning) 콜백을 반환합니다.
예를 들어 useEffect() 훅 안에서 사용할 때는 항상 정리 콜백을 반환해야 합니다.
그렇지 않으면 같은 이벤트 핸들러가 여러 번 등록될 수 있어요.
:::
기본 동작 비활성화 (Disabling the default behavior)
사용 사례에 따라 이벤트가 취하는 기본 동작을 비활성화해야 할 수도 있어요. 이벤트 핸들러에 전달되는 MuiEvent에는 기본 동작이 실행될 수 있는 시기를 제어하는 defaultMuiPrevented 속성이 있습니다. true로 설정하면 이벤트의 기본 처리를 차단하고 나만의 처리를 구현할 수 있어요.
<DataGrid
onCellClick={(params: GridCellParams, event: MuiEvent<React.MouseEvent>) => {
event.defaultMuiPrevented = true;
}}
/>
일반적으로 셀을 더블클릭하면 편집 모드(edit mode)로 들어갑니다. 다음 예시는 사용자가 Ctrl 키도 누르도록 요구해 이 동작을 변경합니다.
import { DataGrid } from '@mui/x-data-grid';
import { useDemoData } from '@mui/x-data-grid-generator';
export default function DoubleClickWithCtrlToEdit() {
const { data, loading } = useDemoData({
dataSet: 'Commodity',
rowLength: 100,
maxColumns: 6,
editable: true,
});
return (
<div style={{ height: 300, width: '100%' }}>
<DataGrid
onCellDoubleClick={(params, event) => {
if (!event.ctrlKey) {
event.defaultMuiPrevented = true;
}
}}
{...data}
loading={loading}
/>
</div>
);
}
이벤트 카탈로그 (Catalog of events)
행을 펼쳐 각 이벤트를 사용하는 방법을 확인하세요.
import * as React from 'react';
import { HighlightedCode } from '@mui/internal-core-docs/HighlightedCode';
import Box from '@mui/material/Box';
import Typography from '@mui/material/Typography';
import { styled } from '@mui/material/styles';
import {
DataGridPro,
GridToolbarContainer,
GridToolbarQuickFilter,
} from '@mui/x-data-grid-pro';
import events from './events.json';
function getDataGridComponentNameFromProjectName(project) {
switch (project) {
case 'x-data-grid':
return 'DataGrid';
case 'x-data-grid-pro':
return 'DataGridPro';
case 'x-data-grid-premium':
return 'DataGridPremium';
default:
throw new Error('Invalid grid project name');
}
}
const Description = styled(Typography)({ whiteSpace: 'nowrap' });
function EventRow({ event }) {
const example = React.useMemo(() => {
const args = ['details, // GridCallbackDetails'];
if (event.event) {
args.unshift(`event, // ${event.event}`);
}
if (event.params) {
args.unshift(`params, // ${event.params}`);
}
const propExample = event.componentProp
? `
// Component prop (available on ${event.projects
.map(getDataGridComponentNameFromProjectName)
.join(', ')})
<DataGrid
${event.componentProp}={handleEvent}
{...other}
/>`
: '';
return `
const handleEvent: GridEventListener<'${event.name}'> = (
${args.join('\n ')}
) => {...}
// Imperative subscription
apiRef.current.subscribeEvent(
'${event.name}',
handleEvent,
);
// Hook subscription (only available inside the scope of the grid)
useGridEvent(apiRef, '${event.name}', handleEvent);
${propExample}
`;
}, [event]);
return (
<Box sx={{ px: 1 }}>
<HighlightedCode code={example} language="tsx" />
</Box>
);
}
const COLUMNS = [
{
field: 'name',
headerName: 'Name',
width: 200,
renderCell: ({ value }) => <code>{value}</code>,
},
{
field: 'plan',
headerName: 'Available on',
width: 100,
align: 'center',
valueGetter: (value, row) => {
if (row.projects.includes('x-data-grid')) {
return 'x-data-grid';
}
if (row.projects.includes('x-data-grid-pro')) {
return 'x-data-grid-pro';
}
if (row.projects.includes('x-data-grid-premium')) {
return 'x-data-grid-premium';
}
return null;
},
renderCell: ({ value }) => {
if (value === 'x-data-grid-pro') {
return <span className="plan-pro" title="Pro plan" />;
}
if (value === 'x-data-grid-premium') {
return <span className="plan-premium" title="Premium plan" />;
}
return '';
},
},
{
field: 'description',
headerName: 'Description',
flex: 1,
renderCell: ({ value }) => (
<Description
variant="body2"
style={{ whiteSpace: 'normal' }}
dangerouslySetInnerHTML={{
__html: value,
}}
/>
),
},
];
function Toolbar() {
return (
<GridToolbarContainer sx={{ p: 1 }}>
<GridToolbarQuickFilter />
</GridToolbarContainer>
);
}
export default function CatalogOfEventsNoSnap() {
return (
<DataGridPro
disableColumnReorder
autoHeight
rows={events}
columns={COLUMNS}
getRowId={(row) => row.name}
getDetailPanelContent={({ row }) => <EventRow event={row} />}
getDetailPanelHeight={() => 'auto'}
getRowHeight={() => 'auto'}
disableRowSelection
hideFooter
slots={{
toolbar: Toolbar,
}}
sx={{
'&.MuiDataGrid-root--densityCompact .MuiDataGrid-cell': { py: '8px' },
'&.MuiDataGrid-root--densityStandard .MuiDataGrid-cell': { py: '15px' },
'&.MuiDataGrid-root--densityComfortable .MuiDataGrid-cell': { py: '22px' },
}}
/>
);
}