typescriptmaterial-uivitereact-tsxmui-x-charts

Need to resolve type error on MUI Barchart


I have developed a barchart with some fancy logic for bar labels which works in development but will not build unless I resolve the type error. I have tried extending BarChartProProps without success. barLabel expects to have a string returned. I needed to implement it like this because I needed a line break between the two elements and the label doesn't render the line break otherwise. Here is the code

<BarChartPro
                layout="horizontal"
                dataset={ aggSummary }
                series={ [
                    {
                        id: 'Demand',
                        dataKey: 'mtd_facility_out_recycled',
                        label: 'Demand',
                        stack: '1',
                        color: '#FFD9D9',
                    },
                    {
                        id: 'Supply',
                        dataKey: 'mtd_recycling_out_recycled',
                        label: 'Supply',
                        stack: '1',
                        color: '#B9B9B9'
                    }
                ] }
                barLabel={ ({seriesId, value}) => {
                    const formattedValue = Number(value).toLocaleString()
                    return (
                        <tspan>
                            <tspan x={ 0 } dy="-0.4em" fontWeight="bold">{ seriesId }</tspan>
                            <tspan x={ 0 } dy="1.5em">{ formattedValue }</tspan>
                        </tspan>
                    )
                } }
                leftAxis={ {
                    tickSize: 0,
                    tickLabelInterval: () => false
                } }
                bottomAxis={ {
                    tickSize: 0,
                    tickLabelInterval: () => false
                } }
                slotProps={ {
                    legend: {hidden: true}
                } }

            />

it renders the following enter image description here


Solution

  • Here was the necessary type augmentation

    declare module '@mui/x-charts-pro' {
        // Extend BarLabelItem for the relevant fields
        interface BarLabelItem {
            seriesId: string;
            value: number;
        }
    
        // Ensure BarSeries picks up the change
        interface BarSeries {
            barLabel?: (params: BarLabelItem) => React.ReactNode;
        }
    
        // If the issue is directly linked to BarChartProProps
        interface BarChartProProps {
            barLabel?: (params: { seriesId: string; value: number }) => React.ReactNode;
        }
    }