[Chartjs]-Accessing a slice of a react-chartjs Pie chart

1👍

After looking under Pie component’s hood, I ended up finding the answer.
You can find it inside componentDidMount():

import React, { Component } from 'react';
import { Pie } from 'react-chartjs-2';

class PieChart extends Component {
    componentDidMount() {
        const change = {
            sliceIndex: 0,
            newOuterRadius: 100
        }
        const meta = this.pie.props.data.datasets[0]._meta;
        meta[Object.keys(meta)[0]]
            .data[change.sliceIndex]
            ._model
            .outerRadius = change.newOuterRadius;
    }

    render() {
        const data = {
            type: 'pie',
            datasets: [ { data: [10, 20, 30] } ],
            labels: ['a', 'b', 'c'],
        };
        const options = {};

        return <Pie
            ref={(self) => this.pie = self}
            data={data}
            options={options}
        />
    }
}

export default PieChart;

1👍

I have one more solution with version 4.3.1.
Try to add offset property into datasets.

import { Pie } from 'react-chartjs-2';

<Pie
    data={
      datasets: [
        {
          data: [1, 1],
          borderColor: ['black', 'transparent'],
          offset: [10, 0],
        },
      ],
    }
/>

It will render Pie with 2 segments. For the first segment, you will have black border and 10px offset

Leave a comment