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

Clearing Up CSS Height Definitions

Based on my observations from other posts, it seems that to establish the height of an element in percentages or pixels, etc., the parent element's height also needs to be explicitly defined. This implies that the height settings must be specified all ...

I designed my radio buttons to ensure they cannot be selected multiple times

I have developed a basic React custom controlled radio button: export const Radio: FC<RadioProps> = ({ label, checked, onChange, disabled, }) => { const id = useId(); return ( <div> <label htmlFor={id} ...

The webpage is unreachable on localhost after attempting to write to a file using node.js

I'm currently attempting to update a file using Node.js. I have a form that contains checkboxes, and upon form submission, the server should update the file based on which checkboxes are selected: a, b, or c. The JSON file structure is as follows: { ...

Error in Axios: The requested resource lacks the 'Access-Control-Allow-Origin' header

I'm having an issue sending form data to MongoDB using Axios in the frontend. The API works when I send a post request using Postman, but it fails when coming from the frontend. Here's a screenshot of the error: Frontend Code: const res = aw ...

Understanding @@iterator in JavaScript: An in-depth look

Can someone shed some light on the mysterious @@iterator? It keeps popping up in tutorials but no one seems to provide a clear explanation of what it actually is. Is it a symbol literal or something else entirely? ...

Ways to showcase every resource from an API in React JS

I need help with adding code to display products along with their images from an API in my existing code. Can someone assist me with this? import React, {useState, useEffect} from 'react' import "bootstrap/dist/css/bootstrap.min.css" im ...

`Modified regions determined by cursor location`

I am working with a split layout featuring two columns, and I need the ability to make each column separately scrollable. Due to using a specialized scroll-to function, I cannot use overflow-y: scroll; or overflow: auto;. I am looking for alternative solut ...

tips for transforming a javascript string into a function invocation

I am faced with the challenge of turning the string logo.cr.Button into a function call. Here is the code I'm working with: logo.cr.Button = function(){ //something } var strg = 'logo.cr.Button'; strg(); When I attempt to execute strg(); ...

Learn the process of extracting a particular value from JSON data and displaying it in HTML by utilizing AngularJS's ng-repeat directive

As a newcomer to angularjs, I am encountering difficulties retrieving and displaying a specific value from a json file in order to showcase it on my view page using angularjs ng-repeat for image source. My goal is to repeat the json file based on a particu ...

Personalize Autocomplete CSS based on the TextField input in React Material UI when a value is present

In my current project, I am utilizing React Material Autocomplete fields, which includes a nested TextField. I have successfully implemented standard styles for when the field is empty and only the label is visible, as well as different styles for hover ef ...

Numerous objects come into view as you scroll

I found a code snippet online that animates items as they appear on scroll. However, the code only triggers animation for one item at a time. How can I modify the code to trigger the animation for all items? const observer = new IntersectionObserver(e ...

Data manipulation with Next.js

_APP.JS function MyApp({ Component, pageProps }) { let primary = 'darkMode_Primary'; let secondary = 'darkMode_Secondary' return ( <Layout primary_super={primary} secondary_super={secondary}> <Component {...page ...

Reacting to the surprise of TS/JS async function behaving differently than anticipated

It appears that I'm facing a challenge with the small method; not sure if my brain is refusing to cooperate or what's going on. async fetchContacts() { await this.http.get('http://localhost:3000/contacts') .subscribe(res =& ...

What steps can be taken to resolve the issue of receiving the error message "Invalid 'code' in request" from Discord OAuth2?

I'm in the process of developing an authentication application, but I keep encountering the error message Invalid "code" in request when attempting to obtain a refresh token from the code provided by Discord. Below is a snippet of my reques ...

Cause: Trying to serialize an `object` that is not JSON serializable (such as a "[object Date]"). Ensure that only JSON serializable data types are returned

Currently, I am utilizing Prisma along with Next.js. My issue arises when attempting to retrieve content from Prisma within the getStaticProps function; while it successfully fetches the data, I encounter difficulties passing it on to the main component. e ...

Ways to showcase numerous products within a single category label

views.py : def get_meals(request): template = loader.get_template('café/meals.html') meal_data = MealInfo.objects.all() category_data = MealsCategory.objects.all() context = { 'meals': meal_data, ' ...

Discover an Effective Approach for Transmitting Form-Data as a JSON Object

Hey there! I'm encountering a bit of an issue with sending some data as a JSON object. The problem arises when trying to send images using FormData. It seems like I need to convert my form data into a single JSON object. Can anyone assist me with this ...

Exploring the effectiveness of React Hook Form using React Testing Library

My Component includes a form that, upon submission, utilizes Apollo's useLazyQuery to fetch data based on the form values. The form in the component is managed by React Hook Forms, with the handleSubmit controlled by RHF. <FormContainer onSubmit= ...

Integrate Thymeleaf properties seamlessly into JavaScript code

I am attempting to embed a property from Spring's application.properties into JavaScript. It is working properly with the following code: <h1 th:utext="${@environment.getProperty('key')}"></h1> However, it returns null with th ...

"Use jQuery to toggle the slide effect for the first element of a

Below is the HTML code snippet: <div class="row header collapse"> Content 1 <i class="fas fa-chevron-circle-up" ></i> </div> <div class="instructions-container"> <div></di ...