reactjsnivo-react

React, Nivo: Passing custom valueFormat function as props to PieChart


I am trying to pass a custom valueFormat function as props so the arcLabels will be rendered with an trailing "%" to a PieChart. While this works pretty well with simple expressions, I do not get it to work with an arrow function. I am fairly new to coding so I hope this is an easy one for you experienced guys.

What works

Calling the PieChart with a simple expression as a prop:

valueFormat: ">-~",

into:

valueFormat={props.valueFormat}

Using the arrow function for "%" as hard coded attribute, so no call with a prop:

valueFormat={value =>            
${Number(value).toLocaleString('en-EN', {
            minimumFractionDigits: 2,
        })} %`
    }

What doesn't work

Calling the PieChart with an arrow function as a prop:

valueFormat:{{value =>
${Number(value).toLocaleString('en-EN', {minimumFractionDigits: 2,
        })} %`
    }}

into:

valueFormat={props.valueFormat}

I tried:

I cannot be sure that I didn't do any mistakes, though.

At this point I am just trying things without understanding anything. Hope you guys can give me a quick hint. Currently I simply built a second PieChart component and hard-coded it into the second.

Thanks in advance!


Solution

  • Thanks to your post I was now able to put it in a const and pass it as a prop of the PieCompanySizes which then creates the Pie (ResponsivePie) and passes the valueFormat as a prop to it, like this:

    PieCompanySizes:

    const PieCompanySizes = () => {
      const valueF = (value) =>
        `${Number(value).toLocaleString("en-EN", { minimumFractionDigits: 2 })}%`;
      return (
        <div className="flex mt-5 relative xs:mr-[-16px]">
          <PieChart
            {...{
              data: piedata,
              arcLabels: true,
              arcLabelsRadiusOffset: 0.5,
              translateX: 0,
              translateY: 45,
              itemsSpacing: 10,
              endAngle: 360,
              width: 320,
              height: 500,
              margin: { top: -65, right: 20, bottom: 80, left: 20 },
              valueFormat: valueF,
            }}
            ...
    

    Pie (from Nivo):

    const PieChart = (props) => {
      const theme = useTheme();
      const colors = tokens(theme.palette.mode);
     return (
        <Pie
          data={props.data}
          width={props.width}
          height={props.height}
          margin={props.margin}
          enableArcLabels={props.arcLabels}
          valueFormat={props.valueFormat}
          ...
    

    Just so no one is confused: I am using <Pie> instead of <ResponsivePie> as fiddling around with CSS flex and the zero-height issue of Nivo Pies created too much headache for me to solve at that point.

    Thank you! :)