简体   繁体   中英

How to push specific items in a new array during a map?

I'm mapping over an array of objects. I only want to display the items that can fit in a single line. The other ones have to be pushed in a new array, that will be displayed elsewhere (a "see more button" + a popover).

In order to do it, I have a ref on the div that encompasses the mapped items. Once its height changes, I know I'm on another line, and that it's time to stop displaying items.

I wrote:

 const Component = ({myArray}) => { let ref = React.useRef(); const { height, width } = useSize(ref); const availableSpace = 24; const otherArray = []; return ( <div ref={ref} style={{display: "flex" flexWrap:"flew-wrap"}}> {myArray.map({label} => { height > 24 && otherArray.push({label}); return ( //stuff ) })} {otherArray && otherArray.length > 0 && ( <button onClick={()=> showRemainingItemsInAPopover}> +{otherArray.length} </button> )} ) }

Sadly, React renders all the items, and then pushes all of them again in otherArray.

How to properly separate my array in two in real time?

Thanks!

Maybe you can use filter function :

 <div ref={ref}>
  {myArray.map({label} => {
    height > 24 && otherArray.push({label});
    return (
        //stuff
     )
  }).filter(() => height <= 24)}

but i'd like to see more code to you help more.

Not sure how many items are in your array and if you are trying to do this for performance reasons...

Could you not use css to set a max-height: 24px; overflow: hidden; max-height: 24px; overflow: hidden; and then use React to toggle the max-height property?

Ie. https://codesandbox.io/s/red-wind-9c94z?fontsize=14&hidenavigation=1&theme=dark

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM