Get height of an element in useEffect hook

Viewed 717

I need to get the correct height of an element after render in order to apply a responsive padding.

I have a component which is a background video with a fixed height 550px. I am trying to position a color overlay on top of that, and a text/button on top of that.

To do this, the text/button is placed in a container with id "hero-content-container" that should have a vertical padding equal to

(550 - document.getElementById('hero-headline').getBoundingClientRect().height) / 2

This way the overlay covers the entire video component. I have tried getBoundingClientRect().height and offsetHeight and both return the correct height for the button, but it returns 138 for text when the correct rendered height is 201.

I am doing this in useEffect, my guess is maybe it is giving me the height before some CSS is applied that changes the text size? But I am not sure. Below is the full code.

import React, { useState, useEffect } from 'react'
import Row from 'react-bootstrap/Row';
import Col from 'react-bootstrap/Col';
import Container from 'react-bootstrap/Container';
import Button from 'react-bootstrap/Button';
import sourceVideo from "../assets/videos/hero.mp4"

const Hero = props => {
  const { toggleModal } = props
  const [padding, setPadding] = useState('100px 0')

  useEffect(() => {
    const headlineHeight = document.getElementById('hero- 
 headline').getBoundingClientRect().height
    const buttonHeight = document.getElementById('hero-button').getBoundingClientRect().height
    const height = headlineHeight + buttonHeight
    console.log(headlineHeight, buttonHeight, height)
    const verticalPadding = ((550 - height) / 2) + 'px'
    setPadding(`${verticalPadding} 0`)
  }, [])

  return (
    <Row className="my-auto" id="hero">
      <Col>
        <div className="video-container">
          <video id="vid" width="100%" height="550" autoPlay loop>
            <source src={sourceVideo} type="video/mp4" />
          </video>
        </div>
        <div style={{ padding: padding }} id="hero-content-container" className="white-overlay my-auto">
          <Container>
            <h1 id="hero-headline">Lorem Ipsum Doler Sit Amet</h1>
            <Button id="hero-button" onClick={toggleModal}>Lorem Ipsum</Button>
          </Container>
        </div>
      </Col>
    </Row>

  )

}

export default Hero

Relevant CSS:

.video-container {
  position: absolute;
  height: 550px;
  z-index: -1;
}

.video-container video {
  object-fit: cover;
}
.white-overlay {
  background:rgba(35,87,137,.6);
  z-index: 999;
}

h1 {
  font-size:56px;
  color:white;
}
0 Answers
Related