diff --git a/src/components/Breadcrumbs/Breadcrumbs.tsx b/src/components/Breadcrumbs/Breadcrumbs.tsx index d29768ad77..27388ac140 100644 --- a/src/components/Breadcrumbs/Breadcrumbs.tsx +++ b/src/components/Breadcrumbs/Breadcrumbs.tsx @@ -53,6 +53,7 @@ interface BreadcrumbsState { const RESIZE_THROTTLE = 200; const MORE_ITEM_WIDTH = 34; const DEFAULT_POPUP_PLACEMENT = ['bottom', 'top']; +const GAP_WIDTH = 4; const b = block('breadcrumbs'); @@ -98,20 +99,22 @@ export class Breadcrumbs extends Re } private container: React.RefObject; - private resizeObserver: ResizeObserver; + private resizeObserver?: ResizeObserver; constructor(props: BreadcrumbsProps) { super(props); this.handleResize = _throttle(this.handleResize, RESIZE_THROTTLE); - this.resizeObserver = new ResizeObserver(this.handleResize); + if (typeof window !== 'undefined') { + this.resizeObserver = new ResizeObserver(this.handleResize); + } this.container = React.createRef(); this.state = Breadcrumbs.prepareInitialState(props); } componentDidMount() { this.recalculate(); - this.resizeObserver.observe(this.container.current as Element); + this.resizeObserver?.observe(this.container.current as Element); } componentDidUpdate(prevProps: BreadcrumbsProps) { @@ -121,7 +124,7 @@ export class Breadcrumbs extends Re } componentWillUnmount() { - this.resizeObserver.disconnect(); + this.resizeObserver?.disconnect(); } render() { @@ -216,17 +219,25 @@ export class Breadcrumbs extends Re private recalculate() { const {items: allItems, lastDisplayedItemsCount, firstDisplayedItemsCount} = this.props; + const availableWidth = this.container.current?.offsetWidth || 0; - if (this.container.current) { + if (this.container.current && availableWidth > 0) { const dividers: HTMLElement[] = Array.from( this.container.current.querySelectorAll(`.${b('divider')}`), ); - const items: HTMLElement[] = Array.from( - this.container.current.querySelectorAll(`.${b('item')}`), + const items: HTMLElement[] = [ + ...(Array.from( + this.container.current.querySelectorAll(`.${b('switcher')}`), + ) as HTMLElement[]), + ...(Array.from( + this.container.current.querySelectorAll(`.${b('item')}`), + ) as HTMLElement[]), + ]; + + const itemsWidths = items.map( + (elem, i) => + elem.scrollWidth + (i === items.length - 1 ? GAP_WIDTH : GAP_WIDTH * 2), ); - - const availableWidth = this.container.current.offsetWidth; - const itemsWidths = items.map((elem) => elem.scrollWidth); const dividersWidths = dividers.map((elem) => elem.offsetWidth); const buttonsWidth = itemsWidths.reduce((total, width, index, widths) => { const isLastItem = widths.length - 1 === index;