Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

element.current.scrollHeight not returning real height (React, CSS)

I have a <div> container that will be populated with some tags as the user selects options on a dropdown. If the tags fill the space I designated for the container, I want to display a "+N" tag with the remaining number of selected options.

Expected output: the isOverflowing condition sets to true.

Actual output: isOverflowing is never set to true.

CODE

const [selectedOptions, setSelectedOptions] = useState<number[]>([]);
const [overflowing, setOverflowing] = useState(false);

const tagsRef = useRef<HTMLDivElement>(null);

const isOverflowing = (element: any) => {
  return element.current?.scrollHeight > element.current?.clientHeight; // NEVER RETURNS TRUE
};

useLayoutEffect(() => {
  if (isOverflowing(tagsRef)) {
    setOverflowing(true);
  } else {
    setOverflowing(false);
  }
}, [tagsRef, selectedOptions]);

...

return (
  <TagsWrapper ref={tagsRef} className="tagsWrapper">
    {selectedOptions.map((option, index) => (
      ...
    ))}
  </TagsWrapper>
)

CSS

.tagsWrapper {
  display: flex;
  flex-flow: row wrap;
  max-height: 32px;
  max-width: calc(100% - 50px - 16px - 4px);
  overflow: hidden;
}

Console logging the tagsRef always shows that scrollHeight and clientHeight are the same, when in fact they are not (I can see that the div is taller when I inspect it on the browser).

I've tried many combinations of max-height, height... to no avail. If the overflow property is set to visible it works, obviously, but I don't want to show the remaining tags... Is there a solution I'm not seeing?

Thanks!

like image 421
Helena Sánchez Avatar asked Aug 06 '26 04:08

Helena Sánchez


1 Answers

I managed to see my own problem. The max-height and overflow properties should be on the parent element of overflowing container:

<TagsContainer>
  <TagsWrapper ref={tagsRef} className="tagsWrapper">
    {selectedOptions.map((option, index) => (
      ...
    ))}
  </TagsWrapper>
</TagsContainer>
.tagsContainer {
  max-height: 32px;
  overflow: hidden;
}
.tagsWrapper {
  display: flex;
  flex-flow: row wrap;
  ...
}
like image 160
Helena Sánchez Avatar answered Aug 07 '26 17:08

Helena Sánchez



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!