I am creating a Dropdown with single and multi selection, and I'm stuck on a feature I want to implement for the multi selection variant, but don't know how to continue.
For reference, here's the full Dropdown implementation. https://codesandbox.io/s/dropdown-ytm4yy
In the src/dropdown/components/multi-value-container.jsx, is where I have the multi selection Dropdown container. Here is its full code.
import { useState, useRef, useLayoutEffect } from "react";
export const MultiValueContainer = ({ selected }) => {
const [isOverflowing, setIsOverflowing] = useState(false);
const selectedCount = selected.length;
const ref = useRef();
useLayoutEffect(() => {
const parentRect = ref.current?.getBoundingClientRect();
const parentWidth = parentRect.width;
const childNodes = [...ref.current.childNodes];
const childNodesWidth = childNodes.map(
(child) => child.getBoundingClientRect().width
);
const childNodesWidthSum = childNodesWidth.reduce((acc, sum) => acc + sum);
childNodesWidthSum > parentWidth
? setIsOverflowing(true)
: setIsOverflowing(false);
}, [selected]);
return (
<div ref={ref} className="react-dropdown__multi-value-container">
{!isOverflowing &&
selected.map((option) => (
<div key={option.value} className="react-dropdown__multi--selected">
{option.label}
</div>
))}
{isOverflowing && (
<div className="react-dropdown__multi--selected max-width">
{selectedCount} items selected
</div>
)}
</div>
);
};
What I am trying to do is this: if the selected children's total width is larger than the container's (gave it a ref), then I want to display x items selected.
I've implemented something that works (check useLayoutEffect, but with flaws, because for example, if I select a number of items and they overflow, the x items selected is showing as expected, but on the next selection, the ref.current.childNodes will look and check that I have only one chip rendered (the x items selected one), whose width is not exceeding the container's width, so it will continue to add to that another one.
How can I fix this?