Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

184
Views
TypeError: Cannot read properties of undefined (reading 'getBoundingClientRect')

I keep getting the error TypeError: Cannot read properties of undefined (reading 'getBoundingClientRect') and don't know why. I'm using the React localhost (Node.js)

import React,{useRef,useState} from 'react';
import { Card } from '../components';
import { CardItemContainer } from './card-item';

export function CardContainer() 
 {
const ref=useRef();

    let distance =ref.current.getBoundingClientRect().x-50; 
    const [scroll,setScroll]=useState('left')

    return(
        <Card>
        
            <Card.ListTitle> Continue to watch</Card.ListTitle>
            <Card.Wrapper>
                <Card.ArrowSliderLeft setScroll={setScroll}  ref={ref}/>
                <Card.List scroll={scroll}  >
                  <CardItemContainer/>
                  <CardItemContainer/>
                  <CardItemContainer/>
                </Card.List>
                <Card.ArrowSliderRight setScroll={setScroll} />
            </Card.Wrapper>
        </Card>
    )
}
about 4 years ago · Juan Pablo Isaza
2 answers
Answer question

0

On the first render the ref value is undefined simply because it gets it's value later after the real DOM has been constructed.

You need to have this case handled when calculating the distance

const distance =ref.current ? ref.current.getBoundingClientRect().x-50 : DEFAULT_DISTANCE; 
about 4 years ago · Juan Pablo Isaza Report

0

The React ref's current value won't be defined/set yet on the initial render. Use a null check on the current value, nullish coalescing to provide a fallback value.

I also suggest using a useEffect hook so you're not also doing this as an unintentional side-effect.

const distance = ref.current?.getBoundingClientRect().x ?? 0 - 50;

or

let distance;

useEffect(() => {
  distance = ref.current?.getBoundingClientRect().x ?? 0 - 50; 
});
about 4 years ago · Juan Pablo Isaza Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!