MiddleTextTruncation
A utility component for truncating long texts in the middle.
Usage
When displaying texts with constrains on its width, the MiddleTextTruncation
component can help by truncating long texts in the middle with an ellipsis ("…"
). This ensures that the beginning and the end of the text remain visible.
import * as React from 'react';
import { MiddleTextTruncation } from '@itwin/itwinui-react';
export default () => {
return (
<MiddleTextTruncation
className='demo-container'
text='MyTitleWithAReallyLongNameThatWillBeTruncatedBecauseItIsReallyThatLongSoHardToBelieve'
/>
);
};
For more examples, see truncation in Select.
Number of end characters
By default, six characters are left visible at the end of the truncated text. This ensures that important suffixes, such as file extensions or identifiers, remain visible. This number can be modified through the endCharsCount
prop to suit user’s specific needs.
import * as React from 'react';
import { MiddleTextTruncation } from '@itwin/itwinui-react';
export default () => {
return (
<MiddleTextTruncation
className='demo-container'
endCharsCount={15}
text={
'ThisIsMyVeryLongFileNameWithImportantExtension_FinalVersion_V2.docx'
}
/>
);
};
Customization
For further control over the rendering of the content, the textRenderer
prop allows users to provide a custom rendering function. This function takes originalText
and truncatedText
as parameters and returns a ReactNode
.
import * as React from 'react';
import { MiddleTextTruncation } from '@itwin/itwinui-react';
export default () => {
return (
<MiddleTextTruncation
className='demo-container'
text='MyTitleWithAReallyLongNameThatWillBeTruncatedWithCustomizedStylingBecauseItIsReallyThatLongSoHardToBelieve'
textRenderer={(truncatedText) => <b>{truncatedText}</b>}
/>
);
};
Accessibility
This component only truncates the content visually but leaves the full content in the accessibility tree. That way, users using assistive technologies can still have access to the full content. This is also consistent with the browser’s default text-overflow
behavior.
However, this behavior may cause some inconvenience for screen-reader users, as the accessible text can become overly verbose. Thus, we recommend taking this into consideration when planning the UX.
Props
Prop | Description | Default |
---|---|---|
text | Text to truncate. string | |
endCharsCount | Number of characters to leave at the end. number | 6 |
textRenderer | Custom renderer for the truncated text. (truncatedText: string, originalText: string) => ReactNode | |
as | "symbol" | "object" | "span" | "a" | "abbr" | "address" | "area" | "article" | "aside" | "audio" | "b" | "base" | "bdi" | "bdo" | "big" | "blockquote" | "body" | "br" | "button" | ... 159 more ... | FunctionComponent<...> |