Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

180
Visualizações
Inconsistent useRef().clientHeight

I have a parent div card which can display one of three child divs. I want to adjust the height of the parent div to fit the exact contents of the currently-visible child div.

To do this, I create a updateDonationCardSize function which reads the refs of all three views, and depending on which one should be currently visible, sets the parent div height to match the appropriate child div height.

function updateDonationCardSize() { // Sets the size of the card to fit contents
    const height = stepOneContainerRef.current.clientHeight
    setDonationCardSize(prevState => ({
        ...prevState,
        ['width']: paymentFooterRef.current.clientWidth,
        ['height']: height
    }))
}

I call this function whenever any of the refs pointing to one of the subviews updates.

useEffect(() => {
    updateDonationCardSize()
    setTimeout(() => updateDonationCardSize(), 700)
}, [stepOneContainerRef, stepTwoContainerRef, stepThreeContainerRef])

Notice the silly approach above where the function is called twice, once immediately and once after a brief delay. For some reason, the first time it runs, it returns the wrong height of 830 whereas the second time it runs, it returns the correct height of 700.

What's even stranger is that if I print out height variable as well as the stepOneContainerRef object into the console next to each other, the height variable is returned as 830 while stepOneContainerRef object actually displays its current.clientWidth property as 700...

I am completely clueless and have spent hours over this already.

Edit - Providing additional information

The parent div contains the following structure:

<div id='parent div' className='overflow-hidden'>
    <div id='parent of dynamic content'>
        <div id='containerOne' className='relative' style={stepOneContainerStyle} />
        <div id='containerTwo' className='relative' style={stepTwoContainerStyle} />
        <div id='containerThree' className='relative' style={stepThreeContainerStyle} />
    </div>
    <div id='footer' />
</div>

and the stepXContainerStyle is a dictionary which sets position: top and x to 0 if it the particular div should be currently visible, otherwise it moves it outside of the overflow region to hide it.

about 4 years ago · Juan Pablo Isaza
1 Respostas
Responde à pergunta

0

The different heights are result of unfinished DOM mutations during the rendering of the components. To fix that change useEffect hook to useLayoutEffect which fires synchronously after all DOM mutations. It will allow you to call updateDonationCardSize only once.

In addition, you should wrap updateDonationCardSize with useCallback for correct hook dependency specification.

const updateDonationCardSize = useCallback(() => { // Sets the size of the card to fit contents
    setDonationCardSize(prevState => ({
        ...prevState,
        ['width']: paymentFooterRef.current.clientWidth,
        ['height']: stepOneContainerRef.current.clientHeight
    }))
}, [paymentFooterRef, stepOneContainerRef]);

useLayoutEffect(() => {
    updateDonationCardSize()
}, [updateDonationCardSize])

I'd also recommand to try solve this problem with CSS rules - it looks like a CSS problem more than component rendering problem.

about 4 years ago · Juan Pablo Isaza Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda