Exploring the Height of a Div
I am interested in monitoring the height of a div element so that I can dynamically adjust distances based on varying screen widths. The animation should respond to changes in screen width, such as when text stacks and the height adjusts accordingly.
For instance, on a full screen the distance is 180, but on narrower screens it is longer. The calculation provided below should give me the correct value (80 added to the current height).
Located in utils/animation.js
window.onload = function getTextDivHeight() {
const divElement = document.querySelector(".textContainer");
const elHeight = divElement.offsetHeight;
const divHeight = elHeight + 80;
console.log(divHeight)
return divHeight;
}
export const textDiv = getTextDivHeight();
Used in components
import { animationStart, textDiv } from "../../utils/animation";
const Video = () => {
return (
<motion.div
initial={{ y: -{textDiv} }} // This value needs to change on page load.
animate={{ y: 0 }}
transition={{ delay: animationStart - 1.5, duration: 1.2 }}
>
<motion.video className="playVideo"
autoPlay muted loop
>
<source src="../../src/assets/video.mp4"/>
</motion.video>
</motion.div>
)
}
The targeted div (in another component)
const IntroText = () => {
return (
<div className="textContainer" id="textContainer"></div>
The issue I am facing is with "divElement" not being defined, possibly due to React's mounting/loading process. Is there a way to access and update this value onload?
My Attempts So Far
I have tried using useEffect and useState without success (as seen in the example below). Despite reading similar posts, I am still encountering errors.
useEffect(() => {
// code ...
divsHeight = something
setDivHeight(divsHeight) // usestate
}, [])