Search code examples
reactjshighcharts

How to change dataLabel style on render in Highcharts?


In the render method, I look for dataLabels that overlap each other and shift them up. But also for such dataLabels I want to change the background color and maybe some other styles. Here is my render:

render: function () {
  const points = this.series[0].points;
  for (var i = 0; i < points.length; i++) {

    if (i < points.length - 1) {
      const dataLabel1 = (points[i] as any).dataLabel
      const dataLabel2 = (points[i + 1] as any).dataLabel

      if ((dataLabel1.x + dataLabel1.width) > dataLabel2.x) {
        dataLabel1.attr({
          y: dataLabel1.y - (dataLabel1.height + 2),
        });
      }
    }
  }
}

I tried to change the styles like this:

dataLabel1.options.style = {
  color: "white"
}

or like this:

dataLabel1.options = {
  style: {
    backgroundColor: "Black"
  }
}

But it has no effect.


Solution

  • If you want to overwrite the datalabel text style instead of using dataLabel.attr() method you need to use dataLabel.css():

    dataLabel1.css({
      color: 'red'
    })
    

    And in case of changing the background it is generated as SVG rect so you need to change the fill attribute:

    dataLabel1.attr({
      y: dataLabel1.y - (dataLabel1.height + 2),
      fill: 'green',
    });
    

    Demo: https://jsfiddle.net/BlackLabel/2rnko8t5/