`useDataset()`
useDataset()
사용자 지정 컴포넌트에서 series와 axes를 채우는 데 사용되는 dataset 배열을 읽습니다.
본문
useDataset() 훅은 차트에 전달된 dataset 배열을 반환합니다.
이는 다음과 같은 경우에 유용합니다:
- 원시 데이터에 접근해야 하는 사용자 지정 컴포넌트를 만들 때
- 차트와 함께 데이터 테이블이나 요약을 만들 때
- 전체 데이터셋에 대한 계산을 수행할 때
:::success 계산된 series 및 axes 데이터가 필요하다면 대신 series 훅과 axis 훅을 사용하세요. :::
사용법 (Usage)
import { useDataset } from '@mui/x-charts/hooks';
function CustomComponent() {
const dataset = useDataset();
// Access the raw dataset array
}
useDataset()은 차트의 dataset prop에 전달된 dataset 배열을 반환하며, dataset이 제공되지 않았다면 undefined를 반환합니다.
기본 예제 (Basic example)
아래 예제는 차트 위에 데이터셋 통계를 표시하기 위해 useDataset()을 사용하는 방법을 보여 줍니다:
import * as React from 'react';
import { useDataset } from '@mui/x-charts/hooks';
import { ChartsDataProvider } from '@mui/x-charts/ChartsDataProvider';
import { ChartsSurface } from '@mui/x-charts/ChartsSurface';
import { LineHighlightPlot, LinePlot } from '@mui/x-charts/LineChart';
import { ChartsXAxis } from '@mui/x-charts/ChartsXAxis';
import { ChartsYAxis } from '@mui/x-charts/ChartsYAxis';
import { ChartsLegend } from '@mui/x-charts/ChartsLegend';
import { ChartsTooltip } from '@mui/x-charts/ChartsTooltip';
import { ChartsAxisHighlight } from '@mui/x-charts/ChartsAxisHighlight';
import Box from '@mui/material/Box';
import Typography from '@mui/material/Typography';
import Paper from '@mui/material/Paper';
const dataset = [
{ month: 'Jan', revenue: 4000, expenses: 2400 },
{ month: 'Feb', revenue: 3000, expenses: 1398 },
{ month: 'Mar', revenue: 2000, expenses: 9800 },
{ month: 'Apr', revenue: 2780, expenses: 3908 },
{ month: 'May', revenue: 1890, expenses: 4800 },
{ month: 'Jun', revenue: 2390, expenses: 3800 },
{ month: 'Jul', revenue: 3490, expenses: 4300 },
];
function DatasetStats() {
const chartDataset = useDataset();
if (!chartDataset) {
return null;
}
const totalRevenue = chartDataset.reduce(
(sum, item) => sum + (typeof item.revenue === 'number' ? item.revenue : 0),
0,
);
const totalExpenses = chartDataset.reduce(
(sum, item) => sum + (typeof item.expenses === 'number' ? item.expenses : 0),
0,
);
const profit = totalRevenue - totalExpenses;
return (
<Paper
elevation={2}
sx={{
p: 2,
mb: 2,
display: 'flex',
gap: 3,
justifyContent: 'space-around',
}}
>
<div>
<Typography variant="caption" sx={{ color: 'text.secondary' }}>
Total Revenue
</Typography>
<Typography variant="h6" color="primary">
${totalRevenue.toLocaleString()}
</Typography>
</div>
<div>
<Typography variant="caption" sx={{ color: 'text.secondary' }}>
Total Expenses
</Typography>
<Typography variant="h6" color="error">
${totalExpenses.toLocaleString()}
</Typography>
</div>
<div>
<Typography variant="caption" sx={{ color: 'text.secondary' }}>
Net Profit
</Typography>
<Typography
variant="h6"
sx={{ color: profit >= 0 ? 'success.main' : 'error.main' }}
>
${profit.toLocaleString()}
</Typography>
</div>
<div>
<Typography variant="caption" sx={{ color: 'text.secondary' }}>
Data Points
</Typography>
<Typography variant="h6">{chartDataset.length}</Typography>
</div>
</Paper>
);
}
export default function UseDataset() {
return (
<ChartsDataProvider
dataset={dataset}
xAxis={[{ dataKey: 'month', scaleType: 'point' }]}
series={[
{
dataKey: 'revenue',
label: 'Revenue',
color: '#1976d2',
type: 'line',
},
{
dataKey: 'expenses',
label: 'Expenses',
color: '#d32f2f',
type: 'line',
},
]}
height={300}
>
<Box sx={{ width: '100%' }}>
<DatasetStats />
<ChartsSurface>
<LinePlot />
<ChartsXAxis />
<ChartsYAxis />
<ChartsAxisHighlight x="line" />
<ChartsTooltip />
<LineHighlightPlot />
</ChartsSurface>
<Box sx={{ display: 'flex', justifyContent: 'center' }}>
<ChartsLegend direction="horizontal" />
</Box>
</Box>
</ChartsDataProvider>
);
}
고급 예제 (Advanced example)
아래 예제는 dataset을 사용해 차트와 동기화 상태를 유지하는 사용자 지정 데이터 테이블을 만드는 방법을 보여 줍니다:
import * as React from 'react';
import { useDataset } from '@mui/x-charts/hooks';
import { ChartsDataProvider } from '@mui/x-charts/ChartsDataProvider';
import { ChartsSurface } from '@mui/x-charts/ChartsSurface';
import { BarPlot } from '@mui/x-charts/BarChart';
import { ChartsXAxis } from '@mui/x-charts/ChartsXAxis';
import { ChartsYAxis } from '@mui/x-charts/ChartsYAxis';
import { ChartsLegend } from '@mui/x-charts/ChartsLegend';
import { ChartsTooltip } from '@mui/x-charts/ChartsTooltip';
import { ChartsAxisHighlight } from '@mui/x-charts/ChartsAxisHighlight';
import { AxisItemIdentifier } from '@mui/x-charts/models';
import Box from '@mui/material/Box';
import Table from '@mui/material/Table';
import TableBody from '@mui/material/TableBody';
import TableCell from '@mui/material/TableCell';
import TableContainer from '@mui/material/TableContainer';
import TableHead from '@mui/material/TableHead';
import TableRow from '@mui/material/TableRow';
import Paper from '@mui/material/Paper';
import Typography from '@mui/material/Typography';
const dataset = [
{ product: 'Product A', q1: 4000, q2: 3000, q3: 2000, q4: 2780 },
{ product: 'Product B', q1: 3000, q2: 1398, q3: 9800, q4: 3908 },
{ product: 'Product C', q1: 2000, q2: 9800, q3: 3000, q4: 4800 },
{ product: 'Product D', q1: 2780, q2: 3908, q3: 4000, q4: 3800 },
{ product: 'Product E', q1: 1890, q2: 4800, q3: 2390, q4: 3800 },
];
function DataTable({
highlightedIndex,
onHighlightedIndexChange,
}: {
highlightedIndex: number | undefined;
onHighlightedIndexChange: (index: number | null) => void;
}) {
const chartDataset = useDataset();
if (!chartDataset) {
return null;
}
const calculateTotal = (item: any) => {
return ['q1', 'q2', 'q3', 'q4'].reduce((sum, quarter) => {
const value = item[quarter];
return sum + (typeof value === 'number' ? value : 0);
}, 0);
};
const calculateQuarterTotal = (quarter: string) => {
return chartDataset.reduce((sum, item) => {
const value = item[quarter];
return sum + (typeof value === 'number' ? value : 0);
}, 0);
};
const grandTotal = chartDataset.reduce(
(sum, item) => sum + calculateTotal(item),
0,
);
return (
<TableContainer component={Paper} sx={{ mt: 3 }}>
<Table size="small">
<TableHead>
<TableRow>
<TableCell>
<strong>Product</strong>
</TableCell>
<TableCell align="right">
<strong>Q1</strong>
</TableCell>
<TableCell align="right">
<strong>Q2</strong>
</TableCell>
<TableCell align="right">
<strong>Q3</strong>
</TableCell>
<TableCell align="right">
<strong>Q4</strong>
</TableCell>
<TableCell align="right">
<strong>Total</strong>
</TableCell>
</TableRow>
</TableHead>
<TableBody>
{chartDataset.map((row, index) => (
<TableRow
key={String(row.product)}
onPointerEnter={() => onHighlightedIndexChange(index)}
onPointerLeave={() => onHighlightedIndexChange(null)}
sx={{
backgroundColor:
highlightedIndex === index ? 'action.hover' : 'transparent',
transition: 'background-color 0.2s',
cursor: 'pointer',
}}
>
<TableCell component="th" scope="row">
{String(row.product)}
</TableCell>
<TableCell align="right">
${typeof row.q1 === 'number' ? row.q1.toLocaleString() : 0}
</TableCell>
<TableCell align="right">
${typeof row.q2 === 'number' ? row.q2.toLocaleString() : 0}
</TableCell>
<TableCell align="right">
${typeof row.q3 === 'number' ? row.q3.toLocaleString() : 0}
</TableCell>
<TableCell align="right">
${typeof row.q4 === 'number' ? row.q4.toLocaleString() : 0}
</TableCell>
<TableCell align="right">
<strong>${calculateTotal(row).toLocaleString()}</strong>
</TableCell>
</TableRow>
))}
<TableRow sx={{ backgroundColor: 'action.hover' }}>
<TableCell>
<strong>Total</strong>
</TableCell>
<TableCell align="right">
<strong>${calculateQuarterTotal('q1').toLocaleString()}</strong>
</TableCell>
<TableCell align="right">
<strong>${calculateQuarterTotal('q2').toLocaleString()}</strong>
</TableCell>
<TableCell align="right">
<strong>${calculateQuarterTotal('q3').toLocaleString()}</strong>
</TableCell>
<TableCell align="right">
<strong>${calculateQuarterTotal('q4').toLocaleString()}</strong>
</TableCell>
<TableCell align="right">
<strong>${grandTotal.toLocaleString()}</strong>
</TableCell>
</TableRow>
</TableBody>
</Table>
</TableContainer>
);
}
export default function UseDatasetAdvanced() {
const [highlightedAxis, setHighlightedAxis] = React.useState<AxisItemIdentifier[]>(
[],
);
const setHighlightedIndexCallback = React.useCallback((index: number | null) => {
if (index === null) {
setHighlightedAxis([]);
} else {
setHighlightedAxis([{ axisId: 'x-axis-id', dataIndex: index }]);
}
}, []);
return (
<ChartsDataProvider
dataset={dataset}
xAxis={[{ id: 'x-axis-id', dataKey: 'product', scaleType: 'band' }]}
series={[
{ dataKey: 'q1', label: 'Q1', stack: 'total', type: 'bar' },
{ dataKey: 'q2', label: 'Q2', stack: 'total', type: 'bar' },
{ dataKey: 'q3', label: 'Q3', stack: 'total', type: 'bar' },
{ dataKey: 'q4', label: 'Q4', stack: 'total', type: 'bar' },
]}
height={300}
highlightedAxis={highlightedAxis}
onHighlightedAxisChange={setHighlightedAxis}
>
<Box sx={{ width: '100%' }}>
<Typography variant="h6" gutterBottom>
Quarterly Sales Report
</Typography>
<ChartsSurface>
<BarPlot />
<ChartsXAxis />
<ChartsYAxis />
<ChartsAxisHighlight x="band" />
<ChartsTooltip />
</ChartsSurface>
<Box sx={{ display: 'flex', justifyContent: 'center' }}>
<ChartsLegend direction="horizontal" />
</Box>
<DataTable
highlightedIndex={highlightedAxis[0]?.dataIndex}
onHighlightedIndexChange={setHighlightedIndexCallback}
/>
</Box>
</ChartsDataProvider>
);
}
반환 값 (Return value)
useDataset()은 다음을 반환합니다:
| Type | Description |
|---|---|
Readonly<DatasetType> | undefined |
차트에 전달된 dataset 배열, 또는 dataset이 제공되지 않았다면 undefined. |
DatasetType은 각 객체가 다양한 속성을 가진 데이터 포인트를 나타내는 객체들의 배열입니다. 예를 들어:
const dataset = [
{ month: 'Jan', sales: 100, expenses: 80 },
{ month: 'Feb', sales: 150, expenses: 90 },
{ month: 'Mar', sales: 120, expenses: 70 },
];
:::info
useDataset()은 차트가 dataset prop을 사용할 때만 값을 반환합니다.
series에 data prop으로 데이터를 전달하면 undefined를 반환합니다.
:::
주의 사항 (Caveats)
이 훅은 차트 컨텍스트 안에서만 사용할 수 있습니다. 사용 요구 사항은 hooks 개요를 참고하세요.