reactjsparentchildrenreact-forwardref

how to get the height of the children from a parent? - React


Sorry for the question. I am new to react. I want to get the height of each child then apply the maximum one on all of them. by the way i do it, i get always the height of the last child. on other hand i don't know exactly how to force the maximum height on all the children. i really appreciate the help.

here is my code :

for the parent component :


 export default function Parent({data, index}) {

   const [testHeight, setTestHeight] = useState([]);
   const listRef = useRef(null);

       useEffect (() => {
        setTestHeight(listRef.current.clientHeight)
     })

    const {
        objects: blocs
    } = data


   return ( 
     <>
          {blocs && Object.values(blocs).map((itemsBlocks, i) => (
                                            <ItemChild dataItem={itemsBlocks} 
                                                          ref={listRef} 
                                                          maxHeight= { testHeight}

                                            />
                                    ))}
     </>
   )
}

for the child component :

const Child = forwardRef(function Child ({dataItem, maxHeight}, ref) {

    useEffect(() => {
        console.log(ref.current.clientHeight);
      })

    const {
        description,
        title
    } = dataItem || {}

    return (
        <>
           <div className="class_child" ref={ref} >
               {maxHeight}
                <p> {title} </p>
                <p> {description} </p>
           </div>

        </>
    )
});

export default Child 


Solution

  • You have multiple issues. First off, you are storing the height, from the parent, and, you seem to be giving the same ref to all of your children ? Each component should have their own ref.

    If you want to get all height, you need to change this :

     useEffect (() => {
       setTestHeight(listRef.current.clientHeight)
     })
    

    You are replacing the value of your testHeight unstead of adding values to the array.

    You should instead, do this :

     useEffect (() => {
       setTestHeight((current ) => [...current, listRef.current.clientHeight])
     })
    

    I advise you to look how to update hooks by using function, as in my reply, to avoid a lot of later trouble you might meet :)

    But, in my opinion, it would be better to update the hook from the children, I'm not sure if you need ref for anything, since you are new to react, I would believe you do not. If you don't need it, then, pass the setTestHeight to children, update it how I showed your, and then you will get all your height, and from the parent, by seeing when your array is full, you will be able to determine your maxheight (that you should store in another hook) and then, update all your children max height

    I'm also not sure why your are using forwardref though.