Home > Back-end >  React returns the height of only the last element from the list of elements
React returns the height of only the last element from the list of elements

Time:02-20

I need to get height of each individual list item. I import ArticlesMenuItem in a parent component and I render them in this way:

const ArticlesMenu = () => {
    const articlesItemRef = useRef(null);
    const renderArticleItems = () => {
        return articleItems.items.map((item, index) => {
            return (
                <ArticlesMenuItem 
                    path={item.path}     
                    label={item.label} 
                    key={item.id} 
                    innerRef={articlesItemRef}
                />
            )
        });
    }
    return (
        <div id="articles" className="clearfix">
            <h2 className="articles__heading">{articleItems.heading}</h2>
            <ul className="articles__list clearfix">
                {renderArticleItems()}
            </ul>
        </div>
    )
}

I the ArticlesMenuItem.js file I want to know the height of each item. But console.log shows only the height of the last item. If the last item has height of 90, it shows 90 for all of the items. If it has 60, then 60 for all of them.

enter image description here

ArticleMenuItem.js looks like this:

import { useRef, useEffect } from 'react';
import { Link } from 'react-router-dom';

const ArticlesMenuItem = ({ path, id, label, innerRef }) => {
    useEffect(() => {
         console.log('innerRef', innerRef.current.clientHeight)
    }, [innerRef.current])

    return (
        <li className="articles__item" ref={innerRef}>
            <Link to={path} className="articles__link" >{label}</Link>
        </li>
    )
}

export default ArticlesMenuItem;

Why does it happen? How can I get real height of each of the items?

CodePudding user response:

You can add useRef as below in the ArticlesMenuItem itself

import { useRef, useEffect } from 'react';
import { Link } from 'react-router-dom';

const ArticlesMenuItem = ({ path, id, label }) => {
    let ref = useRef(null);
    useEffect(() => {
         console.log('innerRef', ref.clientHeight)
    }, [innerRef.current])

    return (
        <li className="articles__item" ref={ref}>
            <Link to={path} className="articles__link" >{label}</Link>
        </li>
    )
}

export default ArticlesMenuItem;

  • Related