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

214
Visualizações
object is possibly "undefined" ts2532

I get the error when I want to make a slider and I have looked for several alternatives to solve it but none of them work. The error is in useEffect(() => {setWidth ( carousel.current.scrollWidth - carousel.current.offsetWidth)}, []); and in carousel.current

import React from "react";
import { motion } from "framer-motion";
import { useRef, useEffect, useState } from "react";
import images from "../images";

function Sliders() {
  const [width, setWidth] = useState(0);
  const carousel = useRef();

  
  useEffect(() => {
    setWidth (carousel.current.scrollWidth -  carousel.current.offsetWidth)
  }, []);

  return (
    <div className="Sliders">
      <motion.div red={carousel} className="carusel" whileTap={{cursor: "grabbing"}} >
        <motion.div drag="x"
          dragConstraints={{ right: 0, left: -width}}
          className="inner-carousel"
        >
          {images.map((image) => {
            return (
              <motion.div className="item" key={image}>
                <img src={image} alt="" />
              </motion.div>
            );
          })}
        </motion.div>
      </motion.div>
    </div>
  );
}

export default Sliders

about 4 years ago · Santiago Gelvez
1 Respostas
Responde à pergunta

0

When the component is launched, initially the value for carousel.current is undefined. Just wrap the statement in if condition, and I believe it should work.

useEffect(() => {
  if (carousel?.current) {
    setWidth (carousel.current.scrollWidth -  carousel.current.offsetWidth)
  }
}, []);

Note: You can try to console carousel.current before return statement to be sure when the object is undefined and at what point it gets populated.

about 4 years ago · Santiago Gelvez 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