Skip to content

How to selectively render only those labels that match a tick for a Line component? #3730

Answered by Yilun-Sun
johansigfrids asked this question in Q&A
Discussion options

You must be logged in to vote

Hi @johansigfrids!

Since you are using an ordinal XAxis and would like to display label for every 10th ticks, the index property from the props it what you need.
For your customized label renderer, you can add an early return with index checking like:

function renderLabel(props) {
  const { x, y, stroke, value, index } = props;
  // Somehow skip rendering labels when the data point does
  // not match up to a tick mark on the x-axis?

  if (!ticks.includes(index)) {
    return null;
  }

  return (
    <text x={x} y={y} dy={0} fill={stroke} fontSize={12} textAnchor="end">
      {value.toFixed(2)}
    </text>
  );
}

And boom!

Here is the codesandbox forked from yours -> demo

Replies: 1 comment 1 reply

Comment options

You must be logged in to vote
1 reply
@johansigfrids
Comment options

Answer selected by johansigfrids
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Category
Q&A
Labels
None yet
2 participants