What is the best way to monitor and record the height of a div element in a React application?

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
    }, [])

Answer №1

If you're looking to grab the height using useRef instead of querySelector, there's a way to achieve that. I created a sandbox showcasing a demo which you can check out here. Simply adjust it according to your requirements by setting the ref in the .textContainer div through useEffect and then passing the height to the component in need.

const divRef = useRef(null);

const [divHeight, setDivHeight] = useState()

useEffect(() => {
  if (divRef.current) {
    console.log(divRef.current)
    setDivHeight(divRef.current.offsetHeight - 5)
  }
}, [])

const IntroText = () => {

    return (
        <div ref={divRef} className = "textContainer" id = "textContainer">

Answer №2

The Resize Observer API provides a solution for this scenario. By utilizing a ref along with it, you can achieve the desired functionality. Here's an example using a <textarea>, which has a built-in resize control on most desktop browsers for testing purposes:

Please note: since Stack Overflow content is primarily in English, the demonstration assumes a horizontal writing-mode. If this does not apply to some of your users, additional logic will be needed for that case. For more information about blockSize and inlineSize, refer to this link.

View Code in TypeScript Playground

textarea { font-size: 1rem; }
<div id="root">Loading&hellip;</div><script src="https://cdn.jsdelivr.net/npm/<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="dcaeb9bdbfa89cede4f2eef2ec">[email protected]</a>/umd/react.development.js"></script><script src="https://cdn.jsdelivr.net/npm/<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="afddcaceccdb82cbc0c2ef9e97819d819f">[email protected]</a>/umd/react-dom.development.js"></script><script src="https://cdn.jsdelivr.net/npm/@babel/<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="552621343b3134393a3b3015627b67667b60">[email protected]</a>/babel.min.js"></script>
<script type="text/babel" data-type="module" data-presets="env,react">

// This Stack Overflow snippet demo uses UMD modules
const { StrictMode, useEffect, useRef, useState } = React;

function useElementHeight(elementRef) {
  const [height, setHeight] = useState(
    () => elementRef.current ? elementRef.current.offsetHeight : 0,
  );

  useEffect(() => {
    if (!elementRef.current) return;
    const element = elementRef.current;

    const updateHeight = (entries) => {
      for (const entry of entries) {
        // Assumes horizontal writing-mode:
        const height = entry.borderBoxSize[0]?.blockSize;
        if (typeof height === "number") setHeight(height);
      }
    };

    const resizeObserver = new ResizeObserver(updateHeight);
    resizeObserver.observe(element, { box: "border-box" });
    return () => resizeObserver.unobserve(element);
  }, [elementRef, setHeight]);

  return height;
}

function App() {
  const ref = useRef(null);
  const height = useElementHeight(ref);
  return <textarea readOnly ref={ref} value={`${height} px`}></textarea>;
}

ReactDOM.createRoot(document.getElementById("root")).render(
  <StrictMode>
    <App />
  </StrictMode>,
);

</script>

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Is it possible to apply styles to the body of a document using styled-components?

Is it possible to apply styles from styled-components to a parent element, such as the <body> tag, in a way that resembles the following: const PageWrapper = styled.div` body { font-size: 62.5%; } ` ...

Retrieving Data from all Rows in jQuery DataTables

Is there a way to copy all rows in jQuery DataTables into a JavaScript array by clicking the header checkbox? https://i.sstatic.net/57dTB.png I need to locate where jQuery DataTables store the HTML for the remaining page of rows so that I can manipulate ...

What is the best way to extract the primary base64 value from reader.result?

After successfully retrieving the base64 value of my file, I noticed that along with the value, I am also getting the type of file and the type of string. However, I only require the actual value in order to send it to the backend. Code for converting fil ...

Trouble with React.PropTypes in function components

Experimenting with ReactJS has been a success so far, but I've encountered an issue with React.PropTypes. Here's the code snippet: const MenuItem = (props) => { return ( <li className="list-group-item"> <sp ...

How can I dynamically change the default value of the selected option dropdown in React-Select when a new option is chosen?

Can you help me understand how to update the default displayed value on a dropdown in a react-select component? When I choose a different option from one dropdown, the select dropdown value does not change. I've attempted this.defaultValue = option.va ...

Media Queries elude my complete comprehension

Can anyone provide a brief overview? For example, should buttons and images, as well as a footer, all be placed in one Media Query or kept separate? I'm feeling overwhelmed by this. ...

Client.db is undefined error encountered in MongoDB backend API

I'm having trouble retrieving data from a collection in my MongoDB backend. Every time I try, I encounter an error stating that the client is not defined. Has anyone else experienced this issue and knows how to resolve it? Error: Client is not define ...

The ES6 method of binding click handlers with parameters in React

After reading numerous articles on the usage of () => {} syntax, binding in the constructor, and binding in the props, I have come to understand that binding this can be performance-intensive. Furthermore, automatic binding with arrow functions incurs a ...

I'm facing a CORS dilemma and I'm seeking assistance to resolve it

I've been struggling with CORS issues and have tried every method possible to resolve it, but without success. Here is the screenshot of my code: https://i.stack.imgur.com/2gTF4.png Below is the request from my React app: https://i.stack.imgur.com/W ...

Oops! Issue encountered: Attempting to access properties of null object (specifically 'map')

<div className="flex flex-col md:flex-row gap-y-2 md:gap-x-2 items-center"> {post.categories.map((category) => ( <div className="bg-[#f7ab0a] text-center text-black px-3 py-1 rounded-full text-sm font-se ...

Issue with publishing npm package using yarn package manager

I'm currently in the process of releasing a fresh package. Utilizing ES6, I've been transpiling my files through babel to start with. However, I've hit a roadblock at this particular stage: https://i.stack.imgur.com/iIVp6.png This part se ...

The versatile aspect of my discord bot is its ability to function with various

It's pretty strange, but my bot seems to respond to different prefixes than what I originally set. Even though I specified "-"" as the prefix in my code, the bot's commands also work with other symbols like "_", ">", "?", etc. I suspect this m ...

Setting an Alias for AVA Tests: A Step-by-Step Guide

I need to set up global aliases in my project without using Webpack or Babel. Currently, I am testing with AVA. The npm package module-alias allows me to define aliases in my package.json file. However, when I try to create a basic example following the d ...

Delve into the world of tackling catastrophic backtracking with regex in Node

Currently, my node.js script includes this regex: const commentPattern = new RegExp( '(\\/\\*([^*]|[\\r\\n]|(\\*+([^*/]|[\\r\\n])))*\\*+/)|(//.*)', 'g&a ...

Connecting onClick event to a dynamically created div using Dojo

While working with dojo 1.9.2, I encountered an issue when trying to add an onClick function to a dynamically created piece of HTML code like so: clickableDiv = "<div data-dojo-attach-point=\"testBtn\">Click Me!</div>"; self.racks.in ...

Having trouble integrating jQuery ui with webpack

I'm having difficulty integrating jQuery UI into my project using webpack. While jQuery is functioning properly, I encounter a warning when navigating to a page that requires jQuery-UI: jQuery.Deferred exception: $(...).draggable is not a function T ...

How can I configure Angular.js in Webstorm?

I'm having trouble setting up a node.js and angular.js project in webstorm as I keep encountering this error message: /usr/bin/node app/src/app.js /home/dac/WebstormProjects/web-plugin/app/src/app.js:1 ion (exports, require, module, __filename, __dir ...

Limiting querySelector to a specific React component: a step-by-step guide

Is there a way to target a specific DOM element within a React component to change its color using the ComponentDidMount method? Parent component export class ListComponent extends Component<...> { render(): ReactNode { return ( ...

Error: Unable to access attributes of an undefined object (looking for 'item')

Every time I attempt to execute the following code, I encounter this error. import React from 'react' import { Accordion} from 'react-bootstrap/Accordion'; import { ToastContainer } from 'react-toastify'; const myaccordion = ( ...

Create an HTML and CSS code that allows you to split paragraph text into columns within a

I am seeking a way to create dynamic paragraph column text using only the Here is an example of how it could be displayed in HTML: <div> <p> Sed ut perspiciatis, unde omnis iste natus error sit voluptatem accusantium doloremque laudantiu ...