Split Chart Labels in Multiple Lines
Environment
| Product Version | 9.0.0 |
| Product | Progress® KendoReact Chart |
Description
In scenarios where the chart labels are too long, resulting in cluttered or unreadable labels, it is necessary to wrap these labels onto multiple lines. This KB article demonstrates how to achieve label wrapping for long X axis labels in a React Chart component by implementing a custom label content function that splits them into multiple lines. The same approach can be used to the other labels in the chart.
This KB article also answers the following questions:
- How can I split the chart labels into multiple lines in KendoReact Chart?
- How can I make long X axis labels more readable in a React Chart?
- Is it possible to wrap X axis labels onto multiple lines in React Charts?
Solution
To wrap long X axis labels in the Chart for React, use the labelContent function within the ChartCategoryAxisItem labels configuration.
Implement your own labels-wrapping functionality using the content or visual template feature. This function allows for the implementation of custom logic to split long labels into multiple lines based on a predefined maximum line width. The following steps and code snippet illustrate how to accomplish this:
-
Define a function to split a given label string into multiple lines. This function takes the label string and a
maxLengthparameter indicating the maximum line width. It returns the modified label with line breaks (\n) inserted where necessary.jsxfunction splitString(str, maxLength) { const words = str.split(' '); let result = ''; let lineLength = 0; for (let i = 0; i < words.length; i++) { const word = words[i]; if (lineLength + word.length > maxLength) { result += '\n'; lineLength = 0; } result += word + ' '; lineLength += word.length + 1; } return result.trim(); } -
Implement the
labelContentfunction to utilizesplitString. This function is assigned to thecontentproperty of the chart's axis labels configuration. ThelabelContenthandler receives label properties as an argument and applies thesplitStringfunction to thedataItem.itemvalue, which represents the current label text.jsxconst labelContent = (props) => { const maxLengthPerLine = 20; const labelsContent = `${props.dataItem.item}`; const result = splitString(labelsContent, maxLengthPerLine); return result; }; -
Apply the custom label content function to the
ChartCategoryAxisItemlabels:jsx<ChartCategoryAxisItem labels={{ visible: true, content: labelContent }} />