I want to to limit the amount of components a parent container component can fit.
Say I have an item container where I render dozens of Item
components. Container has a height limit of 220px
and each Item
has a height of 50px
(for sake of simplicity of this example - real code would have Item
of different height).
Using React, I want to limit amount of Item
components that container can fit, relative to it's height. Therefore, before placing each Item
into the container, I need to verify, whether container doesn't overflow and if it is, stop render more items into it.
I use the following code to achieve this:
const [canRender, setCanRender] = useState(true);
useEffect(() => {
const parent = ref.current.parentElement;
setCanRender(parent.clientHeight <= parent.scrollHeight);
}, []);
In a given example, only 3 Item components should be rendered, because container can't fit more of them. My problem is that React renders all components immediately (due to state not being set synchronously?).
How can I conditionally render Item
component one by one and check for container overflow?