Data Grid - 마스터-디테일 행 패널
Data Grid - 마스터-디테일 행 패널 (Master-detail row panels)
사용자가 Data Grid를 벗어나지 않고 확장 정보를 볼 수 있게 해주는 마스터-디테일 행 패널을 구현해요. 행 항목에 대한 추가 정보를 그리드에서 이동 없이 제공해야 할 때 유용해요.
본문
마스터-디테일 패턴이란?
"마스터-디테일(master-detail)"은 정보를 구성하는 디자인 패턴으로, "마스터" 영역이 데이터를 나열하고 "디테일" 섹션이 각 항목에 대한 추가 정보를 제공해요.
Data Grid Pro는 마스터-디테일 행 패널을 구현하기 위한 도구를 제공해요. 이 패널은 그리드에서 벗어나지 않고 행 항목에 대한 추가 정보를 최종 사용자에게 제공해야 할 때 유용해요.
이 패턴의 일반적인 예는 많은 이메일 클라이언트에서 찾을 수 있어요. 사용자는 마스터 목록에서 이메일을 클릭해 내용(디테일)과 답장, 전달, 삭제 같은 행동을 볼 수 있어요. 행을 펼치려면 + 아이콘을 클릭하거나, 디테일 토글 컬럼의 셀에 포커스된 상태에서 Space를 누르세요:
import * as React from 'react';
import Box from '@mui/material/Box';
import Button from '@mui/material/Button';
import ButtonGroup from '@mui/material/ButtonGroup';
import Divider from '@mui/material/Divider';
import Typography from '@mui/material/Typography';
import Paper from '@mui/material/Paper';
import Stack from '@mui/material/Stack';
import DeleteIcon from '@mui/icons-material/Delete';
import ForwardIcon from '@mui/icons-material/Forward';
import ReplyIcon from '@mui/icons-material/Reply';
import {
DataGridPro,
GridColDef,
useGridApiContext,
GridRowParams,
GRID_DETAIL_PANEL_TOGGLE_FIELD,
useGridSelector,
gridDimensionsSelector,
} from '@mui/x-data-grid-pro';
import { randomCreatedDate, randomEmail } from '@mui/x-data-grid-generator';
function DetailPanelContent({ row: rowProp }: { row: Email }) {
const apiRef = useGridApiContext();
const width = useGridSelector(apiRef, gridDimensionsSelector).viewportInnerSize
.width;
return (
<Stack
sx={{
py: 2,
height: '100%',
boxSizing: 'border-box',
position: 'sticky',
left: 0,
width,
}}
direction="column"
>
<Paper sx={{ flex: 1, mx: 'auto', width: '90%', p: 2 }}>
<Stack direction="column" spacing={1}>
<Typography variant="h5">{`Subject: ${rowProp.subject}`}</Typography>
<Typography variant="caption">{`Date: ${rowProp.date.toLocaleString()}`}</Typography>
<Typography variant="subtitle2">{`From: ${rowProp.name} <${rowProp.email}>`}</Typography>
<Typography variant="subtitle2">{`To: me <${randomEmail()}>`}</Typography>
<Typography variant="body2">
Artisan bitters street art photo booth you probably have not heard of
them slow-carb food truck. Meh narwhal tumeric bodega boys street art
Brooklyn venmo. Kinfolk wolf iceland banjo, pitchfork cupping banh mi
vexillologist cliche locavore venmo. Yuccie kombucha hashtag, bicycle
rights umami truffaut mumblecore Brooklyn neutral milk hotel aesthetic.
Wolf plaid leggings butcher solarpunk shabby chic cliche.
</Typography>
</Stack>
<Divider sx={{ my: 3 }} />
<ButtonGroup variant="text" sx={{ display: 'flex', justifyContent: 'end' }}>
<Button sx={{ px: 2 }} startIcon={<ReplyIcon />}>
Reply
</Button>
<Button sx={{ px: 2 }} startIcon={<ForwardIcon />}>
Forward
</Button>
<Button sx={{ px: 2 }} color="error" startIcon={<DeleteIcon />}>
Delete
</Button>
</ButtonGroup>
</Paper>
</Stack>
);
}
const columns: GridColDef[] = [
{ field: 'name', headerName: 'From', rowHeader: true },
{ field: 'email', headerName: 'Email', width: 200 },
{ field: 'subject', headerName: 'Subject', width: 300 },
{ field: 'date', type: 'date', headerName: 'Date' },
];
const rows = [
{
id: 1,
name: 'Matheus',
email: randomEmail(),
subject: 'Readymade asymmetrical organic salad',
date: randomCreatedDate(),
},
{
id: 2,
name: 'Olivier',
email: randomEmail(),
subject: 'Chillwave solarpunk grailed waistcoat ramps',
date: randomCreatedDate(),
},
{
id: 3,
name: 'Flavien',
email: randomEmail(),
subject: 'Williamsburg ugh YOLO',
date: randomCreatedDate(),
},
{
id: 4,
name: 'Danail',
email: randomEmail(),
subject: 'Humblebrag la croix hexagon big mood',
date: randomCreatedDate(),
},
{
id: 5,
name: 'Alexandre',
email: randomEmail(),
subject: 'Vinyl chambray kitsch',
date: randomCreatedDate(),
},
{
id: 6,
name: 'José',
email: randomEmail(),
subject: 'Hella kogi pour-over wolf',
date: randomCreatedDate(),
},
];
type Email = (typeof rows)[number];
export default function MasterDetailEmailExample() {
const getDetailPanelContent = React.useCallback(
({ row }: GridRowParams) => <DetailPanelContent row={row} />,
[],
);
const getDetailPanelHeight = React.useCallback(() => 400, []);
return (
<Box sx={{ width: '100%', height: 400 }}>
<DataGridPro
columns={columns}
rows={rows}
initialState={{
pinnedColumns: {
left: [GRID_DETAIL_PANEL_TOGGLE_FIELD],
},
}}
getDetailPanelHeight={getDetailPanelHeight}
getDetailPanelContent={getDetailPanelContent}
sx={{
'& .MuiDataGrid-detailPanel': {
overflow: 'visible',
},
}}
/>
</Box>
);
}
마스터-디테일 행 패널 구현하기
마스터-디테일 행 패널을 만들려면 getDetailPanelContent prop에 패널 안에서 렌더링할 콘텐츠를 반환하는 함수를 전달하세요.
유효한 React 요소라면 무엇이든 사용할 수 있어요. 심지어 다른 Data Grid도요.
<DataGridPro getDetailPanelContent={({ row }) => <div>Row ID: {row.id}</div>} />
디테일 패널 높이
기본적으로 디테일 패널의 높이는 500px이에요.
getDetailPanelHeight prop에 함수를 전달해 커스터마이징할 수 있어요.
이 함수는 숫자 또는 "auto"를 반환해야 해요:
- 숫자를 반환하면 패널은 그 값(픽셀)을 높이로 사용해요.
"auto"를 반환하면 높이는 콘텐츠에서 파생돼요.
// 고정 높이:
<DataGridPro
getDetailPanelContent={({ row }) => <div>Row ID: {row.id}</div>}
getDetailPanelHeight={({ row }) => 100}
/>
// 콘텐츠에서 파생된 높이:
<DataGridPro
getDetailPanelContent={({ row }) => <div>Row ID: {row.id}</div>}
getDetailPanelHeight={({ row }) => 'auto'}
/>
:::info
getDetailPanelContent와 getDetailPanelHeight props는 GridRowParams 객체와 함께 호출돼요. 그래서 각 행마다 다른 값을 반환할 수 있어요.
:::
아래 데모는 콘텐츠에서 파생된 높이를 가진 마스터-디테일 패널을 보여줘요:
import * as React from 'react';
import Box from '@mui/material/Box';
import Button from '@mui/material/Button';
import Grid from '@mui/material/Grid';
import Typography from '@mui/material/Typography';
import Paper from '@mui/material/Paper';
import Stack from '@mui/material/Stack';
import DeleteIcon from '@mui/icons-material/Delete';
import {
DataGridPro,
GridColDef,
DataGridProProps,
useGridApiContext,
GridActionsCellItem,
GridActionsCell,
GridRenderCellParams,
} from '@mui/x-data-grid-pro';
import {
randomId,
randomCreatedDate,
randomPrice,
randomCurrency,
randomCountry,
randomCity,
randomEmail,
randomInt,
randomAddress,
randomCommodity,
} from '@mui/x-data-grid-generator';
function generateProduct() {
return {
id: randomId(),
name: randomCommodity(),
quantity: randomInt(1, 5),
unitPrice: randomPrice(1, 1000),
};
}
const DetailPanelActionHandlersContext = React.createContext<
((productId: string) => void) | undefined
>(undefined);
function DetailPanelActionsCell(props: GridRenderCellParams) {
const deleteProduct = React.useContext(DetailPanelActionHandlersContext);
if (!deleteProduct) {
throw new Error('DetailPanelActionHandlersContext is empty');
}
return (
<GridActionsCell {...props}>
<GridActionsCellItem
icon={<DeleteIcon />}
label="delete"
onClick={() => deleteProduct(props.row.id)}
/>
</GridActionsCell>
);
}
function DetailPanelContent({ row: rowProp }: { row: Customer }) {
const apiRef = useGridApiContext();
const addProduct = React.useCallback(() => {
const newProduct = generateProduct();
apiRef.current.updateRows([
{ ...rowProp, products: [...rowProp.products, newProduct] },
]);
}, [apiRef, rowProp]);
const deleteProduct = React.useCallback(
(productId: string) => () => {
const newProducts = rowProp.products.filter(
(product) => product.id !== productId,
);
apiRef.current.updateRows([{ ...rowProp, products: newProducts }]);
},
[apiRef, rowProp],
);
const columns = React.useMemo<GridColDef<Customer['products'][number]>[]>(
() => [
{
field: 'name',
headerName: 'Product',
flex: 1,
editable: true,
rowHeader: true,
},
{
field: 'quantity',
headerName: 'Quantity',
align: 'center',
headerAlign: 'center',
type: 'number',
editable: true,
},
{ field: 'unitPrice', headerName: 'Unit Price', type: 'number' },
{
field: 'total',
headerName: 'Total',
type: 'number',
valueGetter: (value, row) => row.quantity * row.unitPrice,
},
{
field: 'actions',
headerName: '',
type: 'actions',
width: 50,
renderCell: (params) => <DetailPanelActionsCell {...params} />,
},
],
[],
);
return (
<Stack sx={{ py: 2, height: 1, boxSizing: 'border-box' }} direction="column">
<Paper sx={{ flex: 1, mx: 'auto', width: '90%', p: 1 }}>
<Stack direction="column" spacing={1} sx={{ height: 1 }}>
<Typography variant="h6">{`Order #${rowProp.id}`}</Typography>
<Grid container>
<Grid size={{ md: 6 }}>
<Typography variant="body2" color="textSecondary">
Customer information
</Typography>
<Typography variant="body1">{rowProp.customer}</Typography>
<Typography variant="body1">{rowProp.email}</Typography>
</Grid>
<Grid size={{ md: 6 }}>
<Typography variant="body2" align="right" color="textSecondary">
Shipping address
</Typography>
<Typography variant="body1" align="right">
{rowProp.address}
</Typography>
<Typography
variant="body1"
align="right"
>{`${rowProp.city}, ${rowProp.country.label}`}</Typography>
</Grid>
</Grid>
<div>
<Button variant="outlined" size="small" onClick={addProduct}>
Add Product
</Button>
</div>
<div style={{ display: 'flex', flexDirection: 'column', width: '100%' }}>
<DetailPanelActionHandlersContext.Provider value={deleteProduct}>
<DataGridPro
density="compact"
columns={columns}
rows={rowProp.products}
hideFooter
/>
</DetailPanelActionHandlersContext.Provider>
</div>
</Stack>
</Paper>
</Stack>
);
}
const columns: GridColDef[] = [
{ field: 'id', headerName: 'Order ID' },
{ field: 'customer', headerName: 'Customer', width: 200 },
{ field: 'date', type: 'date', headerName: 'Placed at' },
{ field: 'currency', headerName: 'Currency' },
{
field: 'total',
type: 'number',
headerName: 'Total',
valueGetter: (value, row) => {
const subtotal = row.products.reduce(
(acc: number, product: any) => product.unitPrice * product.quantity,
0,
);
const taxes = subtotal * 0.05;
return subtotal + taxes;
},
},
];
function generateProducts() {
const quantity = randomInt(1, 5);
return [...Array(quantity)].map(generateProduct);
}
const rows = [
{
id: 1,
customer: 'Matheus',
email: randomEmail(),
date: randomCreatedDate(),
address: randomAddress(),
country: randomCountry(),
city: randomCity(),
currency: randomCurrency(),
products: generateProducts(),
},
{
id: 2,
customer: 'Olivier',
email: randomEmail(),
date: randomCreatedDate(),
address: randomAddress(),
country: randomCountry(),
city: randomCity(),
currency: randomCurrency(),
products: generateProducts(),
},
{
id: 3,
customer: 'Flavien',
email: randomEmail(),
date: randomCreatedDate(),
address: randomAddress(),
country: randomCountry(),
city: randomCity(),
currency: randomCurrency(),
products: generateProducts(),
},
{
id: 4,
customer: 'Danail',
email: randomEmail(),
date: randomCreatedDate(),
address: randomAddress(),
country: randomCountry(),
city: randomCity(),
currency: randomCurrency(),
products: generateProducts(),
},
{
id: 5,
customer: 'Alexandre',
email: randomEmail(),
date: randomCreatedDate(),
address: randomAddress(),
country: randomCountry(),
city: randomCity(),
currency: randomCurrency(),
products: generateProducts(),
},
];
type Customer = (typeof rows)[number];
export default function DetailPanelAutoHeight() {
const getDetailPanelContent = React.useCallback<
NonNullable<DataGridProProps['getDetailPanelContent']>
>(({ row }) => <DetailPanelContent row={row} />, []);
const getDetailPanelHeight = React.useCallback<
NonNullable<DataGridProProps['getDetailPanelHeight']>
>(() => 'auto' as const, []);
return (
<Box sx={{ width: 1, height: 400 }}>
<DataGridPro
columns={columns}
rows={rows}
getDetailPanelHeight={getDetailPanelHeight}
getDetailPanelContent={getDetailPanelContent}
/>
</Box>
);
}
:::warning
getDetailPanelContent와 getDetailPanelHeight에 제공하는 함수는 항상 메모이즈하세요.
Data Grid는 이 props의 참조값에 의존해 값을 캐시하고 렌더링을 최적화해요.
const getDetailPanelContent = React.useCallback(() => { ... }, []);
<DataGridPro getDetailPanelContent={getDetailPanelContent} />
:::
펼쳐진 디테일 패널 제어하기
어떤 행이 펼쳐질지 제어하려면 detailPanelExpandedRowIds prop에 행 ID 세트를 전달하세요.
onDetailPanelExpandedRowIds prop에 콜백 함수를 전달해 행이 펼쳐지거나 접힐 때를 감지할 수 있어요.
특정 행 패널이 펼쳐진 상태로 Data Grid를 초기화하려면 아래처럼 initialState prop을 사용하세요:
<DataGridPro initialState={{ detailPanel: { expandedRowIds: new Set([1, 2, 3]) } }}>
import * as React from 'react';
import Box from '@mui/material/Box';
import {
DataGridPro,
GridColDef,
GridRowsProp,
GridRowId,
DataGridProProps,
} from '@mui/x-data-grid-pro';
import {
randomCreatedDate,
randomCurrency,
randomEmail,
randomPrice,
} from '@mui/x-data-grid-generator';
import Alert from '@mui/material/Alert';
export default function ControlMasterDetail() {
const [detailPanelExpandedRowIds, setDetailPanelExpandedRowIds] = React.useState(
() => new Set<GridRowId>(),
);
const handleDetailPanelExpandedRowIdsChange = React.useCallback<
NonNullable<DataGridProProps['onDetailPanelExpandedRowIdsChange']>
>((newIds) => {
setDetailPanelExpandedRowIds(newIds);
}, []);
return (
<Box sx={{ width: '100%' }}>
<Alert severity="info">
<code>
detailPanelExpandedRowIds: {JSON.stringify(detailPanelExpandedRowIds)}
</code>
</Alert>
<Box sx={{ height: 400, mt: 1 }}>
<DataGridPro
rows={rows}
columns={columns}
getDetailPanelContent={({ row }) => (
<Box sx={{ p: 2 }}>{`Order #${row.id}`}</Box>
)}
getDetailPanelHeight={() => 50}
detailPanelExpandedRowIds={detailPanelExpandedRowIds}
onDetailPanelExpandedRowIdsChange={handleDetailPanelExpandedRowIdsChange}
/>
</Box>
</Box>
);
}
const columns: GridColDef[] = [
{ field: 'id', headerName: 'Order ID' },
{ field: 'customer', headerName: 'Customer', width: 200, rowHeader: true },
{ field: 'date', type: 'date', headerName: 'Placed at' },
{ field: 'currency', headerName: 'Currency' },
{ field: 'total', type: 'number', headerName: 'Total' },
];
const rows: GridRowsProp = [
{
id: 1,
customer: 'Matheus',
email: randomEmail(),
date: randomCreatedDate(),
currency: randomCurrency(),
total: randomPrice(1, 1000),
},
{
id: 2,
customer: 'Olivier',
email: randomEmail(),
date: randomCreatedDate(),
currency: randomCurrency(),
total: randomPrice(1, 1000),
},
{
id: 3,
customer: 'Flavien',
email: randomEmail(),
date: randomCreatedDate(),
currency: randomCurrency(),
total: randomPrice(1, 1000),
},
{
id: 4,
customer: 'Danail',
email: randomEmail(),
date: randomCreatedDate(),
currency: randomCurrency(),
total: randomPrice(1, 1000),
},
{
id: 5,
customer: 'Alexandre',
email: randomEmail(),
date: randomCreatedDate(),
currency: randomCurrency(),
total: randomPrice(1, 1000),
},
];
디테일 패널 콘텐츠 지연 로딩
디테일 패널용 콘텐츠를 미리 제공할 필요 없어요. 대신 행이 펼쳐질 때 지연 로딩할 수 있어요.
다음 예시에서 <DetailPanelContent /> 컴포넌트는 마운트 시 데이터를 가져와요.
이 컴포넌트는 getDetailPanelContent prop에서 디테일 패널 콘텐츠를 렌더링하는 데 사용돼요.
import * as React from 'react';
import Box from '@mui/material/Box';
import Typography from '@mui/material/Typography';
import Paper from '@mui/material/Paper';
import Stack from '@mui/material/Stack';
import { DataGridPro, DataGridProProps, GridColDef } from '@mui/x-data-grid-pro';
import {
randomEmail,
randomInt,
randomCommodity,
randomPrice,
randomTraderName,
randomId,
} from '@mui/x-data-grid-generator';
import { DataGridProps, GridRowId } from '@mui/x-data-grid';
type Products = Awaited<ReturnType<typeof getProducts>>;
const DetailPanelDataCache = React.createContext(new Map<GridRowId, Products>());
async function getProducts(orderId: Customer['id']) {
await new Promise((resolve) => {
setTimeout(resolve, 1000);
});
const quantity = randomInt(1, 5);
return [...Array(quantity)].map((_, index) => ({
id: index,
orderId,
name: randomCommodity(),
quantity: randomInt(1, 5),
unitPrice: randomPrice(1, 1000),
}));
}
function DetailPanelContent({ row: rowProp }: { row: Customer }) {
const [isLoading, setLoading] = React.useState(true);
const [products, setProducts] = React.useState<
Awaited<ReturnType<typeof getProducts>>
>([]);
const detailPanelDataCache = React.useContext(DetailPanelDataCache);
React.useEffect(() => {
let isMounted = true;
(async () => {
if (!detailPanelDataCache.has(rowProp.id)) {
console.log('fetching detail panel content for row', rowProp.id);
const response = await getProducts(rowProp.id);
// 가상화로 디테일 패널이 마운트 해제될 때 데이터가 유실되지 않도록 캐시에 저장
detailPanelDataCache.set(rowProp.id, response);
}
const result = detailPanelDataCache.get(rowProp.id)!;
if (!isMounted) {
return;
}
setProducts(result);
setLoading(false);
})();
return () => {
isMounted = false;
};
}, [rowProp.id, detailPanelDataCache]);
return (
<Stack
sx={{ py: 2, height: '100%', boxSizing: 'border-box' }}
direction="column"
>
<Paper sx={{ flex: 1, mx: 'auto', width: '90%', p: 1 }}>
<Stack direction="column" spacing={1} sx={{ height: 1 }}>
<Typography variant="h6">{`Order #${rowProp.id}`}</Typography>
<DataGridPro
density="compact"
loading={isLoading}
columns={[
{ field: 'name', headerName: 'Product', flex: 1, rowHeader: true },
{
field: 'quantity',
headerName: 'Quantity',
align: 'center',
type: 'number',
},
{ field: 'unitPrice', headerName: 'Unit Price', type: 'number' },
{
field: 'total',
headerName: 'Total',
type: 'number',
valueGetter: (value, row) => row.quantity * row.unitPrice,
},
]}
rows={products}
sx={{ flex: 1 }}
hideFooter
/>
</Stack>
</Paper>
</Stack>
);
}
const columns: GridColDef[] = [
{ field: 'customer', headerName: 'Customer', width: 200 },
{ field: 'email', headerName: 'Email', width: 200 },
];
function getRow() {
return {
id: randomId(),
customer: randomTraderName(),
email: randomEmail(),
};
}
const rows: ReturnType<typeof getRow>[] = [];
for (let i = 0; i < 100; i += 1) {
rows.push(getRow());
}
type Customer = (typeof rows)[number];
const getDetailPanelContent: DataGridProps['getDetailPanelContent'] = (params) => (
<DetailPanelContent row={params.row} />
);
const getDetailPanelHeight = () => 240;
export default function LazyLoadingDetailPanel() {
const detailPanelDataCache = React.useRef(new Map<GridRowId, Products>()).current;
const handleDetailPanelExpansionChange = React.useCallback<
NonNullable<DataGridProProps['onDetailPanelExpandedRowIdsChange']>
>(
(newExpandedRowIds) => {
// 아직 펼쳐진 디테일 패널의 캐시 데이터만 유지
for (const [id] of detailPanelDataCache) {
if (!newExpandedRowIds.has(id)) {
detailPanelDataCache.delete(id);
}
}
},
[detailPanelDataCache],
);
return (
<Box sx={{ width: '100%', height: 400 }}>
<DetailPanelDataCache.Provider value={detailPanelDataCache}>
<DataGridPro
columns={columns}
rows={rows}
getDetailPanelHeight={getDetailPanelHeight}
getDetailPanelContent={getDetailPanelContent}
onDetailPanelExpandedRowIdsChange={handleDetailPanelExpansionChange}
/>
</DetailPanelDataCache.Provider>
</Box>
);
}
:::warning 자동 높이로 지연 로딩 패널을 사용하면 스크롤 문제가 발생할 수 있어요. 이는 잠시 다시 마운트되는 패널이 가상화기에 의해 DOM에서 제거될 때보다 더 작은 높이를 가지기 때문이에요.
이 경우 마지막 패널 높이를 캐시하고 getDetailPanelHeight에서 그 값들을 제공하세요.
구현 방법은 자동 높이 지연 로딩 디테일 패널(Lazy loading detail panels with auto height) 레시피를 확인하세요.
:::
디테일 패널을 폼으로 사용하기
내장된 행 편집 기능(row editing feature)의 대안으로, 디테일 패널 안에 폼 컴포넌트를 렌더링해 사용자가 행 값을 편집하게 할 수 있어요.
아래 데모는 react-hook-form을 사용해 이 동작을 구현하는 방법을 보여주지만, 다른 폼 라이브러리도 지원돼요.
import * as React from 'react';
import Box from '@mui/material/Box';
import Button from '@mui/material/Button';
import Typography from '@mui/material/Typography';
import Paper from '@mui/material/Paper';
import Stack from '@mui/material/Stack';
import TextField from '@mui/material/TextField';
import { useForm, Controller } from 'react-hook-form';
import {
DataGridPro,
GridColDef,
GridRowModelUpdate,
useGridApiContext,
GridRowParams,
} from '@mui/x-data-grid-pro';
import { randomEmail } from '@mui/x-data-grid-generator';
function DetailPanelContent({ row }: { row: Customer }) {
const apiRef = useGridApiContext();
const {
control,
handleSubmit,
formState: { isValid },
} = useForm({
defaultValues: row,
mode: 'onChange',
});
const onSubmit = (data: GridRowModelUpdate) => {
apiRef.current.updateRows([data]);
apiRef.current.toggleDetailPanel(row.id);
};
return (
<Stack
sx={{ py: 2, height: '100%', boxSizing: 'border-box' }}
direction="column"
>
<Paper sx={{ flex: 1, mx: 'auto', width: '90%', p: 1 }}>
<Stack
component="form"
onSubmit={handleSubmit(onSubmit)}
sx={{
justifyContent: 'space-between',
height: 1,
}}
>
<Typography variant="h6">{`Edit Order #${row.id}`}</Typography>
<Controller
control={control}
name="customer"
rules={{ required: true }}
render={({ field, fieldState: { invalid } }) => (
<TextField
label="Customer"
size="small"
error={invalid}
required
fullWidth
{...field}
/>
)}
/>
<Controller
control={control}
name="email"
rules={{ required: true }}
render={({ field, fieldState: { invalid } }) => (
<TextField
label="Email"
size="small"
error={invalid}
required
fullWidth
{...field}
/>
)}
/>
<div>
<Button
type="submit"
variant="outlined"
size="small"
disabled={!isValid}
>
Save
</Button>
</div>
</Stack>
</Paper>
</Stack>
);
}
const columns: GridColDef[] = [
{ field: 'id', headerName: 'Order ID' },
{ field: 'customer', headerName: 'Customer', width: 200, rowHeader: true },
{ field: 'email', headerName: 'Email', width: 200 },
];
const rows = [
{
id: 1,
customer: 'Matheus',
email: randomEmail(),
},
{
id: 2,
customer: 'Olivier',
email: randomEmail(),
},
{
id: 3,
customer: 'Flavien',
email: randomEmail(),
},
{
id: 4,
customer: 'Danail',
email: randomEmail(),
},
{
id: 5,
customer: 'Alexandre',
email: randomEmail(),
},
];
type Customer = (typeof rows)[number];
export default function FormDetailPanel() {
const getDetailPanelContent = React.useCallback(
({ row }: GridRowParams) => <DetailPanelContent row={row} />,
[],
);
const getDetailPanelHeight = React.useCallback(() => 240, []);
return (
<Box sx={{ width: '100%', height: 400 }}>
<DataGridPro
columns={columns}
rows={rows}
getDetailPanelHeight={getDetailPanelHeight}
getDetailPanelContent={getDetailPanelContent}
/>
</Box>
);
}
조건부 디테일 패널
일부 행에만 디테일 패널이 있다면, 없는 행에 대해 getDetailPanelContent에서 null(또는 undefined)을 반환하세요.
기본 토글 버튼은 행에 콘텐츠가 없을 때 스스로 비활성화하므로, 단지 숨기기 위해 커스텀 토글 컬럼이 필요하지 않아요:
import * as React from 'react';
import Box from '@mui/material/Box';
import Typography from '@mui/material/Typography';
import { DataGridPro, DataGridProProps, GridColDef } from '@mui/x-data-grid-pro';
const columns: GridColDef<(typeof rows)[number]>[] = [
{ field: 'id', headerName: 'Order ID' },
{ field: 'customer', headerName: 'Customer', width: 200, rowHeader: true },
{ field: 'hasNotes', headerName: 'Has notes', type: 'boolean' },
];
const rows = [
{ id: 1, customer: 'Matheus', hasNotes: true, notes: 'Requested gift wrapping.' },
{ id: 2, customer: 'Olivier', hasNotes: false, notes: null },
{ id: 3, customer: 'Flavien', hasNotes: true, notes: 'Asked for a refund.' },
{ id: 4, customer: 'Danail', hasNotes: false, notes: null },
];
export default function DetailPanelConditional() {
// 메모가 없는 행은 `null`을 반환하며, 이는 해당 행의 토글을 비활성화하기에 충분해요.
// 그래서 수동으로 숨길 커스텀 토글 컬럼이 필요하지 않아요.
const getDetailPanelContent = React.useCallback<
NonNullable<DataGridProProps['getDetailPanelContent']>
>(({ row }) => (row.notes ? <Box sx={{ p: 2 }}>{row.notes}</Box> : null), []);
const getDetailPanelHeight = React.useCallback(() => 'auto' as const, []);
return (
<Box sx={{ width: '100%' }}>
<Typography sx={{ mb: 1 }} variant="body2">
Only rows with notes have an enabled toggle.
</Typography>
<Box sx={{ height: 300 }}>
<DataGridPro
columns={columns}
rows={rows}
getDetailPanelHeight={getDetailPanelHeight}
getDetailPanelContent={getDetailPanelContent}
/>
</Box>
</Box>
);
}
디테일 패널 토글 커스터마이징
토글에 사용되는 아이콘을 바꾸려면 icon slot에 다른 컴포넌트를 제공할 수 있어요. 이렇게요:
<DataGridPro
slots={{
detailPanelExpandIcon: CustomExpandIcon,
detailPanelCollapseIcon: CustomCollapseIcon,
}}
/>
또한 컬럼 집합에 field: GRID_DETAIL_PANEL_TOGGLE_FIELD인 컬럼을 추가해 토글 컴포넌트를 완전히 재정의할 수도 있어요.
이렇게 하면 Data Grid가 기본 토글 컬럼을 추가하지 않아요.
그런 다음 다른 컬럼처럼 renderCell()을 사용해 새 토글 컴포넌트를 추가할 수 있어요:
<DataGridPro
columns={[
{
field: GRID_DETAIL_PANEL_TOGGLE_FIELD,
renderCell: (params) => <CustomDetailPanelToggle {...params} />,
},
]}
/>
field가 정의된 유일한 속성이므로, 추가 옵션(예: 필터링, 정렬, 컬럼 메뉴 비활성화)을 구성하는 것은 사용자에게 달려 있어요.
기본 옵션이 미리 구성된 토글을 설정하고 싶다면 컬럼을 정의할 때 GRID_DETAIL_PANEL_TOGGLE_COL_DEF를 펼쳐 넣을 수 있어요. 아래처럼요:
<DataGridPro
columns={[
{
...GRID_DETAIL_PANEL_TOGGLE_COL_DEF, // 이미 올바른 field를 포함
renderCell: (params) => <CustomDetailPanelToggle {...params} />,
},
]}
/>
이 접근 방식을 사용해 토글 컬럼의 위치를 바꿀 수도 있어요. 아래 데모처럼요:
import * as React from 'react';
import Box from '@mui/material/Box';
import IconButton from '@mui/material/IconButton';
import ExpandMoreIcon from '@mui/icons-material/ExpandMore';
import {
DataGridPro,
GridColDef,
GridRowsProp,
GridRenderCellParams,
GridRowParams,
useGridSelector,
useGridApiContext,
gridDetailPanelExpandedRowsContentCacheSelector,
gridDetailPanelExpandedRowIdsSelector,
GRID_DETAIL_PANEL_TOGGLE_COL_DEF,
} from '@mui/x-data-grid-pro';
import {
randomCreatedDate,
randomCurrency,
randomEmail,
randomPrice,
} from '@mui/x-data-grid-generator';
export default function CustomizeDetailPanelToggle() {
const getDetailPanelContent = React.useCallback(
({ row }: GridRowParams) =>
row.id % 2 === 0 ? <Box sx={{ p: 2 }}>{`Order #${row.id}`}</Box> : null,
[],
);
const getDetailPanelHeight = React.useCallback(() => 50, []);
return (
<div style={{ height: 400, width: '100%' }}>
<DataGridPro
rows={rows}
columns={columns}
getDetailPanelContent={getDetailPanelContent}
getDetailPanelHeight={getDetailPanelHeight}
/>
</div>
);
}
function CustomDetailPanelToggle(props: Pick<GridRenderCellParams, 'id' | 'value'>) {
const { id } = props;
const apiRef = useGridApiContext();
// 매번 ´getDetailPanelContent`를 호출하는 것을 피하기 위해, 다음 셀렉터는
// 행 id별 디테일 패널 콘텐츠를 가진 객체를 제공해요.
const contentCache = useGridSelector(
apiRef,
gridDetailPanelExpandedRowsContentCacheSelector,
);
const expandedRowIds = useGridSelector(
apiRef,
gridDetailPanelExpandedRowIdsSelector,
);
const isExpanded = expandedRowIds.has(id);
// 값이 유효한 React 요소가 아니면, 그 행에는 디테일 패널이 없다는 뜻이에요.
const hasDetail = React.isValidElement(contentCache[id]);
return (
<IconButton
size="small"
tabIndex={-1}
disabled={!hasDetail}
aria-label={isExpanded ? 'Close' : 'Open'}
>
<ExpandMoreIcon
sx={(theme) => ({
transform: `rotateZ(${isExpanded ? 180 : 0}deg)`,
transition: theme.transitions.create('transform', {
duration: theme.transitions.duration.shortest,
}),
})}
fontSize="inherit"
/>
</IconButton>
);
}
const columns: GridColDef[] = [
{ field: 'id', headerName: 'Order ID' },
{ field: 'customer', headerName: 'Customer', width: 200, rowHeader: true },
{ field: 'date', type: 'date', headerName: 'Placed at' },
{ field: 'currency', headerName: 'Currency' },
{ field: 'total', type: 'number', headerName: 'Total' },
{
...GRID_DETAIL_PANEL_TOGGLE_COL_DEF,
renderCell: (params) => (
<CustomDetailPanelToggle id={params.id} value={params.value} />
),
},
];
const rows: GridRowsProp = [
{
id: 1,
customer: 'Matheus',
email: randomEmail(),
date: randomCreatedDate(),
currency: randomCurrency(),
total: randomPrice(1, 1000),
},
{
id: 2,
customer: 'Olivier',
email: randomEmail(),
date: randomCreatedDate(),
currency: randomCurrency(),
total: randomPrice(1, 1000),
},
{
id: 3,
customer: 'Flavien',
email: randomEmail(),
date: randomCreatedDate(),
currency: randomCurrency(),
total: randomPrice(1, 1000),
},
{
id: 4,
customer: 'Danail',
email: randomEmail(),
date: randomCreatedDate(),
currency: randomCurrency(),
total: randomPrice(1, 1000),
},
{
id: 5,
customer: 'Alexandre',
email: randomEmail(),
date: randomCreatedDate(),
currency: randomCurrency(),
total: randomPrice(1, 1000),
},
];
:::info
다른 셀 렌더러와 마찬가지로 value prop도 사용할 수 있어요. 이는 행의 상태에 해당하며, 펼침 상태일 때 true, 접힘 상태일 때 false로 설정돼요.
:::
디테일 패널 컬럼 헤더 커스터마이징
디테일 패널 컬럼에 커스텀 헤더를 렌더링하려면 컬럼 정의에서 renderHeader() 속성을 사용하세요.
이 속성은 colDef(컬럼 정의)와 field를 포함하는 GridRenderHeaderParams 객체를 받아요.
다음 스니펫은 이 작업을 하는 방법을 보여줘요:
const columns = [
{
...GRID_DETAIL_PANEL_TOGGLE_COL_DEF,
renderHeader: (params) => (
<div>
<span>{params.colDef.headerName}</span>
<button onClick={() => console.log('Custom action')}>Custom action</button>
</div>
),
},
//... other columns
];
:::success 이 사용 사례의 더 복잡한 예시는 모든 디테일 패널 펼치기/접기(expanding or collapsing all detail panels) 레시피를 참고하세요. :::
디테일 패널 콘텐츠 스크롤 비활성화
기본적으로 디테일 패널의 너비는 모든 컬럼 너비의 합과 같아요.
즉 가로 스크롤바가 있을 때, 스크롤하면 패널 콘텐츠도 함께 스크롤된다는 뜻이에요.
이 동작을 피하려면 디테일 패널의 크기를 Data Grid의 바깥 크기로 설정하세요.
apiRef.current.getRootDimensions()를 사용해 최신 크기 값을 얻으세요.
그리고 패널이 스크롤되지 않게 하려면 position: sticky와 left: 0을 설정하세요.
다음 데모는 이를 달성하는 방법을 보여줘요. 토글 컬럼이 고정되어(pinned) 사용자가 가로로 스크롤할 때 계속 보인다는 점에 주목하세요:
import * as React from 'react';
import Box from '@mui/material/Box';
import Typography from '@mui/material/Typography';
import Paper from '@mui/material/Paper';
import Stack from '@mui/material/Stack';
import {
DataGridPro,
GridColDef,
useGridApiContext,
GridRowParams,
GRID_DETAIL_PANEL_TOGGLE_FIELD,
useGridSelector,
gridDimensionsSelector,
} from '@mui/x-data-grid-pro';
import {
randomCreatedDate,
randomPrice,
randomCurrency,
randomCountry,
randomCity,
randomEmail,
randomInt,
randomAddress,
randomCommodity,
} from '@mui/x-data-grid-generator';
function DetailPanelContent({ row: rowProp }: { row: Customer }) {
const apiRef = useGridApiContext();
const width = useGridSelector(apiRef, gridDimensionsSelector).viewportInnerSize
.width;
return (
<Stack
sx={{
py: 2,
height: '100%',
boxSizing: 'border-box',
position: 'sticky',
left: 0,
width,
}}
direction="column"
>
<Paper sx={{ flex: 1, mx: 'auto', width: '90%', p: 1 }}>
<Stack direction="column" spacing={1} sx={{ height: 1 }}>
<Typography variant="h6">{`Order #${rowProp.id}`}</Typography>
<DataGridPro
density="compact"
columns={[
{ field: 'name', headerName: 'Product', flex: 1, rowHeader: true },
{
field: 'quantity',
headerName: 'Quantity',
align: 'center',
type: 'number',
},
{ field: 'unitPrice', headerName: 'Unit Price', type: 'number' },
{
field: 'total',
headerName: 'Total',
type: 'number',
valueGetter: (value, row) => row.quantity * row.unitPrice,
},
]}
rows={rowProp.products}
sx={{ flex: 1 }}
hideFooter
/>
</Stack>
</Paper>
</Stack>
);
}
const columns: GridColDef[] = [
{ field: 'id', headerName: 'Order ID' },
{ field: 'customer', headerName: 'Customer', width: 200 },
{ field: 'email', headerName: 'Email' },
{ field: 'date', type: 'date', headerName: 'Placed at' },
{ field: 'currency', headerName: 'Currency' },
{ field: 'address', headerName: 'Address' },
{
field: 'city',
headerName: 'City',
valueGetter: (value, row) => `${row.city}, ${row.country.label}`,
},
{
field: 'total',
type: 'number',
headerName: 'Total',
valueGetter: (value, row) => {
const subtotal = row.products.reduce(
(acc: number, product: any) => product.unitPrice * product.quantity,
0,
);
const taxes = subtotal * 0.05;
return subtotal + taxes;
},
},
];
function generateProducts() {
const quantity = randomInt(1, 5);
return [...Array(quantity)].map((_, index) => ({
id: index,
name: randomCommodity(),
quantity: randomInt(1, 5),
unitPrice: randomPrice(1, 1000),
}));
}
const rows = [
{
id: 1,
customer: 'Matheus',
email: randomEmail(),
date: randomCreatedDate(),
address: randomAddress(),
country: randomCountry(),
city: randomCity(),
currency: randomCurrency(),
products: generateProducts(),
},
{
id: 2,
customer: 'Olivier',
email: randomEmail(),
date: randomCreatedDate(),
address: randomAddress(),
country: randomCountry(),
city: randomCity(),
currency: randomCurrency(),
products: generateProducts(),
},
{
id: 3,
customer: 'Flavien',
email: randomEmail(),
date: randomCreatedDate(),
address: randomAddress(),
country: randomCountry(),
city: randomCity(),
currency: randomCurrency(),
products: generateProducts(),
},
{
id: 4,
customer: 'Danail',
email: randomEmail(),
date: randomCreatedDate(),
address: randomAddress(),
country: randomCountry(),
city: randomCity(),
currency: randomCurrency(),
products: generateProducts(),
},
{
id: 5,
customer: 'Alexandre',
email: randomEmail(),
date: randomCreatedDate(),
address: randomAddress(),
country: randomCountry(),
city: randomCity(),
currency: randomCurrency(),
products: generateProducts(),
},
{
id: 6,
customer: 'José',
email: randomEmail(),
date: randomCreatedDate(),
address: randomAddress(),
country: randomCountry(),
city: randomCity(),
currency: randomCurrency(),
products: generateProducts(),
},
];
type Customer = (typeof rows)[number];
export default function FullWidthDetailPanel() {
const getDetailPanelContent = React.useCallback(
({ row }: GridRowParams) => <DetailPanelContent row={row} />,
[],
);
const getDetailPanelHeight = React.useCallback(() => 400, []);
return (
<Box sx={{ width: '100%', height: 400 }}>
<DataGridPro
columns={columns}
rows={rows}
initialState={{
pinnedColumns: {
left: [GRID_DETAIL_PANEL_TOGGLE_FIELD],
},
}}
getDetailPanelHeight={getDetailPanelHeight}
getDetailPanelContent={getDetailPanelContent}
sx={{
'& .MuiDataGrid-detailPanel': {
overflow: 'visible',
},
}}
/>
</Box>
);
}
마스터-디테일 행 패널 레시피
마스터-디테일 행 패널을 커스터마이징하는 더 많은 예시는 다음 레시피를 확인하세요:
- 한 번에 하나의 디테일 패널 펼치기(One expanded detail panel at a time)
- 모든 디테일 패널 펼치기/접기(Expand or collapse all detail panels)
- 행 클릭으로 디테일 패널 토글(Toggling detail panels on row click)
- 자동 높이 디테일 패널 지연 로딩(Lazy loading detail panels with auto height)
apiRef
Data Grid는 마스터-디테일 행 패널 구현 내부에서 사용되는 메서드 집합을 apiRef 객체를 통해 노출해요.
아래 레퍼런스는 관련 함수들을 설명해요.
자세한 내용은 API object를 참고하세요.
:::warning 이 API는 Data Grid의 내장 prop으로는 특정 사용 사례를 해결하기 부족할 때 최후의 수단으로만 사용해야 해요. :::
import ApiDocs from 'docs/src/modules/components/ApiDocs';
import api from 'docs/pages/x/api/data-grid/grid-detail-panel-api.json';
export default function DetailPanelApiNoSnap() {
return <ApiDocs proApi={api} />;
}