Home > OS >  TypeError: Cannot read properties of undefined (reading 'getBoundingClientRect')
TypeError: Cannot read properties of undefined (reading 'getBoundingClientRect')

Time:10-06

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>
    )
}

CodePudding user response:

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; 

CodePudding user response:

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; 
});
  • Related