Implementing a Portfolio Composition Pie Chart
Showcase the creation of a pie chart to represent the composition of a financial portfolio, using TanStack React Charts with dynamic data updates for portfolio changes.
import { Chart } from 'react-charts';
import React, { useState, useEffect } from 'react';
Import necessary modules and React hooks.
function PortfolioCompositionPieChart({ portfolioData }) {
const [data, setData] = useState([{ label: 'Portfolio', data: [] }]);
useEffect(() => {
const chartData = portfolioData.map(asset => {
return { primary: asset.assetName, secondary: asset.value };
});
setData([{ label: 'Portfolio', data: chartData }]);
}, [portfolioData]);
Define the PortfolioCompositionPieChart component accepting portfolio data as props. Use useEffect to transform incoming data into a format accepted by the pie chart.
const series = React.useMemo(
() => ({
type: 'pie'
}),
[]
);
Memoize the series configuration for the pie chart.
const axes = React.useMemo(
() => [
{ primary: true, type: 'ordinal', position: 'bottom' },
{ type: 'linear', position: 'left', stacked: true }
],
[]
);
Memoize the axes configuration. Although not used in the pie chart, this is necessary to comply with the generic chart component structure.
return (
<div style={{ height: '300px' }}>
<Chart data={data} series={series} axes={axes} tooltip />
</div>
);
}
Render the Chart component inside a div container with a specified height. This utilizes the data and series configured for the pie chart.
export default PortfolioCompositionPieChart;
Export the PortfolioCompositionPieChart component for use in other parts of the application.