1 year ago

#89940

test-img

bex

Count number of rows of li items in ul container with React

I was wondering how to measure the number of rows in a container. When it shows more than 3 rows of li, I want the rest of the li items in the rows below to be hidden with a show more/less button.

So far I've measured the rows with the height of the container. "When the height of the ul container is more than 128px (equivalent to 3 rows), hide the li items above that height" is the logic but this doesn't work in hiding the li items based on the below code.

Please could you help me in refactoring the code to get it to work or by providing an alternative method to measure the amount of rows.

Thanks in advance!

Rebecca

    export function ListOfItems(): JSX.Element {

        const [isOpen, setIsOpen] = useState(false);
        const [height, setHeight] = useState(0);
        const ref = useRef(null);

        useEffect(() => {
            setHeight(ref.current?.clientHeight);
        });

        console.log(height);

        return (
            <ListSection title={`List of Items`}>
                <ul className={styles.wrapper} ref={ref}>
                    {list?.map((listItem, height) => (
                        <li
                            key={id}
                            className={classNames({
                                [styles.hidden]: height > 128 && !isOpen,
                            })}
                        >
                            <RoundedPill
                                label={label}
                            />
                        </li>
                    ))}
                </ul>
                <p onClick={() => setIsOpen(!isOpen)}>{isOpen ? "Show less" : "Show more"}</p>
            </ListSection>
        );
    }

javascript

reactjs

html-lists

listitem

0 Answers

Your Answer

Accepted video resources