useIndexOfLastVisibleChild
Sample Usage#
This hook will find the index of the last child of a containing element that fits within its bounding rectangle. This is done by summing the widths of the children until they exceed the width of the container.
() => {const invisibleStyles = {position: 'absolute',left: 0,pointerEvents: 'none',visibility: 'hidden',};const containerElementRef = React.useRef(null);const overflowElementRef = React.useRef(null);const indexOfLastVisibleChild = useIndexOfLastVisibleChild(containerElementRef.current,overflowElementRef.current,);const elements = ['Element 1', 'Element 2', 'Element 3', 'Element 4', 'Element 5', 'Element 6', 'Element 7'];const children = useMemo(() => {const indexOfOverflowStart = indexOfLastVisibleChild + 1;const childrenList = elements.map((element, i) => (<divkey={element}className="px-4 pt-2"style={i >= indexOfOverflowStart ? invisibleStyles : {}}>{element}</div>));const overflowChildren = elements.slice(indexOfOverflowStart).map(overflowChild => (<Dropdown.Item key={`${overflowChild}-overflow`}>{overflowChild}</Dropdown.Item>));const MoreDropdown = (<Dropdown ref={overflowElementRef} style={!overflowChildren.length ? invisibleStyles : {}} key="overflow-example"><Dropdown.Togglevariant="link"id="more-toggle">More...</Dropdown.Toggle><Dropdown.Menu className="dropdown-menu-right">{overflowChildren}</Dropdown.Menu></Dropdown>)childrenList.push(MoreDropdown);return childrenList;}, [indexOfLastVisibleChild]);return (<div className="d-flex" ref={containerElementRef}>{children}</div>)};