Victory-native: How can I add a background color to a label?

Created on 13 Dec 2018  路  2Comments  路  Source: FormidableLabs/victory-native

I added a VictoryLine with a label, but because the label is displayed on top the y-axis I want to give it a solid backgroud color so that the tick label won't shine through. Tried using the textComponent attribute but didn't get it working ...

screenshot 2018-12-13 at 10 02 08

<VictoryLine
  data={[
    { x: new Date(2018, 11, 1, 0, 0, 0), y: 2600 },
    { x: new Date(2018, 11, 7, 0, 0, 0), y: 2600 },
    { x: new Date(2018, 11, 30, 0, 0, 0), y: 2600 },
  ]}
  labels={datum => datum.y}
  labelComponent={
    <VictoryLabel
      renderInPortal
      dx={-4}
      dy={2}
      // textComponent={<Text style={{ background: 'red' }} />}
    />
  }
  domain={{
    x: [new Date(2018, 11, 7, 0, 0, 0), new Date(2018, 11, 13, 0, 0, 0)],
  }}
  scale={{ x: 'time', y: 'linear' }}
  style={{
    data: {
      padding: 0,
      stroke: '#B0BEC5',
      strokeOpacity: 0.8,
      strokeWidth: 2,
      strokeDasharray: [3, 6],
      strokeDashoffset: -1,
      strokeLinecap: 'round',
    },
    labels: {
      fill: '#263238',
      fontFamily: 'Open Sans',
      fontSize: 14,
      fontWeight: '500',
      background: '#fff',
      verticalAnchor: 'start',
      textAnchor: 'end',
    },
  }}
/>

Most helpful comment

ok, found a way ... but how can I calculate the width of the label? I'm currently using a static width, but what if I need it to be dynamic?

const CustomLabel =  props => {
  const { x, y, style } = props;
  const { fontSize } = style;

  return (
    <G>
      <Rect fill="#fff" x={x - 53} y={y + 2} width="52" height={fontSize} />
      <VictoryLabel {...props} />
    </G>
  );
};

And then use this custom label as labelComponent:

labelComponent={
  <VictoryPortal>
    <CustomLabel dx={-4} dy={2} />
  </VictoryPortal>
}

All 2 comments

ok, found a way ... but how can I calculate the width of the label? I'm currently using a static width, but what if I need it to be dynamic?

const CustomLabel =  props => {
  const { x, y, style } = props;
  const { fontSize } = style;

  return (
    <G>
      <Rect fill="#fff" x={x - 53} y={y + 2} width="52" height={fontSize} />
      <VictoryLabel {...props} />
    </G>
  );
};

And then use this custom label as labelComponent:

labelComponent={
  <VictoryPortal>
    <CustomLabel dx={-4} dy={2} />
  </VictoryPortal>
}

I just had to solve this for my own project. Set the Rect width using state, and then use onLayout on the Text element to capture the width and store it in the state variable. There's an example here.

Was this page helpful?
0 / 5 - 0 ratings