Looking to access HTML elements in React without relying on setTimeout?

When developing a component that requires grabbing DOM elements to calculate heights, I initially resorted to using a setTimeout function to ensure the elements are captured once the page loads. While this solution worked perfectly, I am aware that there might be a better approach than relying on setTimeout. I have heard that using useEffect could be a more efficient way to handle this. Here is the current implementation:

const OrderSummaryView = () => {
    const isMobile = useGetBreakpoint() === 'mobile'
    const { versionIsVariant } = useContext(Abtests.Context)
    const isFixedScrollEnabled = versionIsVariant('FIXED_SCROLL_ORDER_SUMMARY') && !isMobile

    const main = document.querySelector('main[class*="main"]')
    const cartItemsContainer = document.querySelector('#cartItems')
    const summaryContainer = document.querySelector('.summaryContainer')

    const [scrollPosition, setScrollPosition] = useState(0)
    const [itemContainerHeight, setItemContainerHeight] = useState(0)
    const [summaryContainerHeight, setsummaryContainerHeight] = useState(0)
    const [calculatedBreakpoint, setCalculatedBreakpoint] = useState(0)

    const handleScroll = () => {
        const position = window.pageYOffset
        setScrollPosition(position)
    }

    useEffect(() => {
        window.addEventListener('scroll', handleScroll, { passive: true })
        return () => {
            window.removeEventListener('scroll', handleScroll)
        }
    }, [])

    setTimeout(() => {
        setItemContainerHeight(cartItemsContainer.clientHeight)
        if (summaryContainer.clientHeight !== 0) {
            setsummaryContainerHeight(summaryContainer.clientHeight)
        }
        setCalculatedBreakpoint(itemContainerHeight - summaryContainerHeight + 100)
    }, 2000)
    const mainHeight = main.clientHeight

    const isSticky = scrollPosition >= 90 && isFixedScrollEnabled && (scrollPosition < calculatedBreakpoint)
    const isPostSticky = (scrollPosition >= calculatedBreakpoint) && isFixedScrollEnabled

    const orderSummaryClassname = `orderSummary${isSticky ? `Div__is-sticky` : isPostSticky ? `Div__post-sticky` : 'Div'}`
    const postStickyTop = `${mainHeight - summaryContainerHeight - 50}px`

    return (
        <div className="summaryContainer">
            <div className={orderSummaryClassname}
                style={isPostSticky ? { top: postStickyTop } : isSticky ? { top: '10px' } : null}>
                <OrderSummaryTitle title="Order Summary" />
                <OrderSummaryBody isFixedScrollEnabled={isFixedScrollEnabled} />
                <DesignerCashback />
            </div>
        </div>
    )
}

export default OrderSummaryView


Answer №1

Implementing useEffect might be a valuable option.

Don't forget to refer to the React Docs

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

Add a variety of images

Looking for help with uploading multiple images to a folder and saving paths in the database? Here's a code snippet I've been working on: The issue I'm facing is that while the image names are being saved in the database, the actual images ...

Tips for adjusting the offset dimensions in Bootstrap 4 grid systems

Incorporating Bootstrap 4 into my Angular 8 application, I am faced with an issue on the main page where I have two components sized md-5 and md-6, respectively. To create a gap between them, I used offset-md-1. However, the offset size is too large, res ...

Error: accessing 'map' property of undefined during API retrieval

I am currently working on a project for a full stack blog site. I have successfully created an API for the back-end and it is functioning properly as I am able to retrieve posts from it. However, when I attempt to iterate through the posts using map, I enc ...

Issue encountered when starting astro following framework selection

Trying to kickstart astro and running into an issue when not selecting a framework. Even though git is installed and fully operational, the error persists. Any assistance would be greatly appreciated. √ Which frameworks would you like to use? » > C ...

Display class name in React only when the variable is set to true

import React from 'react'; import logo from './logo.svg'; import './App.css'; function App() { return ( <div className="App"> <h1 className={ isTrue ? 'primary' : ''}>{ fa ...

The flexibility of the flex-wrap property does not extend to affect nested elements

Check out this example first: http://jsfiddle.net/8ofrs0y7/14/ <div class="flex-group"> <ul class="flex-container red"> <li class="flex-item"&g;1</li> <li class=&qu ...

Responsive dropdown menu in Bootstrap 5 navbar

Update: I successfully fixed the desktop version. Now, I just need to work on making it responsive for mobile. The problem I am encountering is that the dropdown menu doesn't function properly on both mobile and desktop. Although the styling looks go ...

Trouble with Firebase import despite successful installation

I attempted to create a basic website to gain knowledge about Firebase 9, but I am facing issues when trying to import firebase files. I have searched for tutorials on configuring firebase, but they either do not address my problem or are based on older v ...

How to Turn Off Animation in React Material UI Tooltips

I've integrated React Material UI's Tooltip Component into my React project. import Tooltip from "@material-ui/core/Tooltip"; ... ... <Tooltip title="Add" arrow> <Button>Arrow</Button> </Tooltip> ... ... Is there a w ...

What are the steps to create a downpour in every location on Earth

Is there a way to create a continuous raining effect for my weather app using CSS only? I have achieved a satisfactory look, but the rain effects seem to only cover random chunks of the screen rather than the entire screen. How can I make it cover the enti ...

Display information using HTML elements within a loop in JavaScript

I am facing an issue with iterating over an array of objects in JavaScript. Each object contains multiple parameters, and my goal is to extract the data from each object and display it in a table or a grid format. Here is an example of my code: function ...

Tips for using jQuery dropdown menus

I am currently in the process of creating a prototype for a quick dropdown menu using jQuery. However, I have reached the limits of my knowledge on jQuery and could use some assistance in solving my issue. My objective is to have a dropdown animate down w ...

What is the best way to incorporate link tags into text in AngularJS?

I'm struggling with making links within strings clickable in Angular. Can anyone provide guidance on how to accomplish this? One of the string examples from my JSON data is: "I’m hosting #AFF Catwalk Show @Bullring on 27th Sept with @BillieFaiers. ...

Once I deployed my Nextjs website on Vercel, I encountered an issue when attempting to log in with Google as it kept redirecting me to localhost:

I rely on supabase for my backend operations. While attempting to log in using Google, I need to ensure that it does not redirect me to localhost. ...

Personalize the breakpoints of Bootstrap 4's grid system

In my project, I am facing a situation where I need a 1280 breakpoint to switch from desktop to tablet, instead of the xl breakpoint at 1200 as defined in Bootstrap. How can I globally change the xl breakpoint in Bootstrap without recompiling from the sour ...

How can you modify the breakpoint values in a MUI theme to make it responsive?

I'm currently using the v1 beta version of MUI. I've noticed that the media query breakpoints in MUI are different from those in Bootstrap v4, which I am also using. I would like to override the default MUI breakpoint values to align them with Bo ...

Challenge with the Bootstrap 3 grid structure involving nesting

On my .aspx page, I have the code snippet below: .cDiv { background-color: gray; } .tColor { background-color:yellow; } .tColor2 { background-color:blue; } <div class="container"> <div class="row"> <div class="col-sm-9 tColor" ...

What would cause a flex-basis calculation to throw an error in SASS?

Today, I was working on a flex-grid generator in scss, which is something I do often. However, I encountered an unexpected error this time. I am using a 12-col-grid system and my approach should work fine with the code flex: 0 0 #{100 / 12 / $i}%;. There m ...

AdBlock causing image display issue in Firefox with bootstrap and Wordpress

My Wordpress + Bootstrap code is not displaying images in Firefox, despite working fine in other browsers. I tried disabling ad-block as suggested on SO, but it didn't help. I'm stuck. Here's the HTML snippet: <div class="navbar-collap ...

Video posters can now feature a sleek black border to enhance the

How can I add a black border to a video poster? I've tried to work it out on my own, but I'm having trouble getting it to work. Thank you for any assistance... echo '<video id="video" width="300px" height="200px&q ...