Skip to content

Instantly share code, notes, and snippets.

@tomemmerson
Last active October 22, 2021 21:50
Show Gist options
  • Save tomemmerson/c7668ec04591475d49daaeb4e695ce53 to your computer and use it in GitHub Desktop.
Save tomemmerson/c7668ec04591475d49daaeb4e695ce53 to your computer and use it in GitHub Desktop.
Nivo rounded top corners on @nivo/bar

So, you're looking to have rounded corners...

To do this I use a custom barComponent and make a minor change to the @nivo/bar source

This is what my barComponent looks like:

const CHART_HEIGHT = 300; // Set this to the height of your chart.

const CustomBarComponent = (props: any) => {
    const {
      x,
      y,
      width,
      height,
      color,
      data,
      showTooltip,
      hideTooltip,
    } = props;
    /* This is the amount of overlap each bar will have (either 10px or 0).
       The condition is to ensure that the overlap doesn't happen on the bottom 
       SVG element causing it to overlap the x-axis */
    const overlap = y + height >= CHART_HEIGHT ? 0 : 10;

    return (
      <g
        transform={`translate(${x}, ${y})`}
      >
        {height > 0 && (
          <path
            id='Rectangle_969'
            data-name='Rectangle 969'
            d={`M8,0H${width}a8,8,0,0,1,8,8V${
              height + overlap
            }a0,0,0,0,1,0,0H0a0,0,0,0,1,0,0V8A8,8,0,0,1,8,0Z`}
            fill={color}
          />
        )}
      </g>
    );
  };

The above will produce rounded corners but you will have this happening: Broken rounded corners As you can see the bottom bar has been overlapped by the top one, thus making it look like it doesn't have any rounded corners.

Sadly there isn't a way around this other than changing the order that the SVG elements are added to the DOM, which needs to be done via the @nivo/bar source.

Luckily we can just update this line: https://github.com/plouc/nivo/blob/95bbe5c283d9fa42aba6e7c52ba1c4c295724178/packages/bar/src/Bar.tsx#L163 to reverse the barsWithValue array.

Or if we want to, like I did, because i'm lazy, you can use https://www.npmjs.com/package/patch-package instead of having to fork @nivo.

Note: This only works if animate=false - Look a little further up the file lines below and swap that array instead if you want animations...

To do this just update the package directly, depending on the way you're importing it - update the following:

  • line 1014 of @nivo/bar/dist/nivo-bar-es.js to }).reverse().map(function (d) {
  • line 1021 of @nivo/bar/dist/nivo-bar-cjs.js to the same
  • line 1009 of @nivo/bar/dist/nivo-bar-umd.js to the same

then patch the package, yarn patch-package @nivo/bar

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment