I have an array of elements and I want to display them in a div, when the array is big some elements are outside my parent div, I want to detect which ones are outside to make some operations.
this is my example :
export default function App() {
const data = [
{ id: 1, name: "test1" },
{ id: 2, name: "test2" },
{ id: 3, name: "test3" },
{ id: 4, name: "test4" },
{ id: 5, name: "test5" },
{ id: 6, name: "test6" },
{ id: 7, name: "test7" },
{ id: 8, name: "test8" }
];
return (
<div
style={{
height: "120px",
background: "red",
display: "flex",
flexDirection: "column"
}}
>
{data.map((el) => (
<div key={el.id}>{el.name}</div>
))}
</div>
);
}
So, the output should be :
{ id: 7, name: "test7" },
{ id: 8, name: "test8" }
the goal of this is to display in parent ONLY the elements that parent can support to display, forthe others I will display it in other div
2
Answers
To detect which elements are outside the parent div, you can make use of React refs and DOM measurements.
and created a new component for VisibleItems
import React from "react";
Since your parent div is fixed height of 120px, if you give the children fixed height as well then you can easily calculate the children that will contain inside the parent.
if child height is 30px, then the parent can only contain 120/30= 4 children.
I don’t think there is any specific way to detect a child overflowing it’s parent.