Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

195
Visualizações
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 Respostas
Responde à pergunta

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 Relatório

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 Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda