Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to style YAxis recharts to make it ellipsis if label too long?

Spec:

  1. Recharts ver: 2.0.9
  2. ReactJS ver: 17.0.2
  3. Browser: Chrome Version 91.0.4472.77 (Official Build) (x86_64)
  4. OS: MacOS

Background:

I'm trying to use recharts package to create a chart. I'm pretty close with my goal. But, I'm stuck in styling the YAxis Label to make it ellipsis if the label is too long.

Current Condition:

Here is the current condition

As you can see, it's overlapping with the other data. I know I can make the font-size smaller or set the width to be bigger. But, the problem is, the YAxis Label are dynamic and it could be long. Here is the current code https://codesandbox.io/s/simple-bar-chart-forked-72z60?file=/src/App.tsx

Objective:

I want to make the YAxis Label to display "This is long label and..." (showing three dots if it's too long), kind like using ellipsis.

Btw, I have same problem as this question Dynamic height for Recharts horizontal barchart with long labels in YAxis. You may mark this as duplicate, but please, also help me. Those question still doesn't have accepted answer.

like image 364
Akza Avatar asked Sep 14 '25 14:09

Akza


1 Answers

You can achieve it using one of YAxis props, tickFormatter. This props return each YAxis value and it's index. Also, this props need a string as the return value, which is formatted YAxis label. The idea is kind of like this:

tickFormatter = (value: string, index: number) => {
   const limit = 20; // put your maximum character
   if (value.length < limit) return value;
   return `${value.substring(0, limit)}...`;
};

<YAxis
   width={150}
   tickFormatter={tickFormatter}
/>
like image 58
prowse Avatar answered Sep 16 '25 11:09

prowse