cssreactjsmui-xmui-x-charts

Apply font style to MUI X BarChart Legend


How can I apply simple font-style (change the size) to a React/Material-UI x-charts BarChart Legend text element? The documentation suggests that:

Since the library relies on SVG for rendering, you can customize them as you do with other MUI components with CSS overriding. Chart components accept the sx props. From here, you can target any subcomponents with its class name.

However I have been unable to make any custom styling work?

I have tried creating and then using a StyledBarChart with my custom styling:

import { styled } from '@mui/material/styles';
import { BarChart } from "@mui/x-charts/BarChart";

const StyledBarChart = styled(BarChart)(({ theme }) => ({
    theme,
    "& .MuiChartsLegend-series text": {
        fontSize: '0.8em',
    },
}));

export default StyledBarChart;

and have tried using the sx property on the BarChart component as well:

<BarChart
  sx={{ "& .MuiChartsLegend-series text": { fontSize: "0.8em" } }}
  dataset={...}
  series={[...]}
  xAxis={...}
/>

However in all instances, the legend text element receives styling which overrides all my CSS styles? My final HTML always ends up looking like:

<text 
  x="11"
  y="0"
  text-anchor="start"
  dominant-baseline="central"
  style="font-family:
    Montserrat, sans-serif;
    font-weight: 400;
    font-size:1rem;
    line-height: 1;
    color: inherit;
    fill: rgba(0, 0, 0, 0.87);"
  >
  <tspan x="11" dy="0px" dominant-baseline="central">My Legend Text Item</tspan>
</text>

Is there a way to customize this font-size for these legends somehow?


Solution

  • The only thing that worked for me was adding !important to the style:

    <BarChart
      ...
      sx={{ "& .MuiChartsLegend-series text": { fontSize: "0.7em !important" }, }}
    />