Search code examples
chartspie-chartrecharts

Tooltip not working correctly with activeIndex on pie charts(ReCharts)


Pie charts that utilize Tooltip and activeIndex do not work correctly. The tooltip will not show up unless you re-enter the same sector. When you are not in the same sector it shows the Warning: Failed prop type: Invalid prop activeIndex supplied to Pie.

<PieChart
        className="pie-chart"
        width={this.props.width ? this.props.width : 500}
        height={375}
        onMouseEnter={this.onPieEnter}
      >
        <Pie
          dataKey="value"
          data={data}
          // cx={250}
          // cy={100}
          activeIndex={
            this.state.activeIndex === undefined
              ? 0
              : this.state.activeIndex
          }
          activeShape={this.renderActiveShape}
          outerRadius={
            this.state.width <= 1025 && this.state.width > 768 ? 80 : 100
          }
          innerRadius={
            this.state.width <= 1025 && this.state.width > 768 ? 65 : 85
          }
          fill="#8884d8"
          onMouseEnter={this.onPieEnter}
        >
          {data.map((entry, index) => (
            <Cell
              key={index}
              fill={this.COLORS[index % this.COLORS.length]}
            />
          ))}
        </Pie>
</PieChart>

Default active index always set so when you are not in the same sector pie tooltip shows.


Solution

  • When you are not in the same sector then the activeIndex is changed automatically and it returns the object type, and actually, activeIndex is number type so I check for a shouldComponentUpdate method and it returns true if activeIndex is number only.

    So if the activeIndex type is not a number then component will not be updated and activeIndex state is remains the same as the previous state, so tooltip is not hidden any time.

    This code works for me.

    shouldComponentUpdate(nextProps, nextState) {
        return typeof nextState.activeIndex === "number";
    }