Empresas
Empleos
  • Sobre nosotros
  • Soluciones
    • Publicación de vacantes
      Publica tu vacante y recibe candidatos calificados en 48h.
    • Evaluación de candidatos
      500+ pruebas técnicas y psicológicas, más anti-fraude.
    • Headhunting
      Búsqueda ejecutiva a la medida de principio a fin.
    • Nómina + EOR
      Dispersión de nómina y EOR en más de 15 países de LATAM.
  • Precios
  • Empleos

0

126
Vistas
Useref returning an error when switching view

I have an component with an useEffect method inside. And inside this useEffect method, there I created a useRef to handle some scroll effects and animations. Particularly, the const ref = useRef(null); . It works fine, however, upon switching views where this ref is not being used, it gives an error. Please see below code and picture:

   import React, { useEffect, useRef, useCallback } from 'react';
import styled from 'styled-components';
import { Anchor, Link } from '../components/AllSvgs';

const Container = styled.div`
  position: relative;
`;
const Slider = styled.div`
  position: fixed;
  top: 0;
  right: 2rem;
  display: flex;
  justify-content: center;
  align-items: center;
  flex-direction: column;
  transform: translateY(-100%);
  .chain {
    transform: rotate(135deg);
  }
`;

const PreDisplay = styled.div`
  position: absolute;
  top: 0;
  right: 2rem;
`;

const AnchorComponent = (props) => {
  const ref = useRef({
    style: {
      transform: null
    }
  })
  const hiddenRef = useRef();

  useEffect(() => {
    const handleScroll = () => {
      let scrollPosition = window.pageYOffset;
      let windowSize = window.innerHeight;
      let bodyHeight = document.body.offsetHeight;

      let diff = Math.max(bodyHeight - (scrollPosition + windowSize));
      //diff*100/scrollposition
      let diffP = (diff * 100) / (bodyHeight - windowSize);

      ref.current.style.transform = `translateY(${-diffP}%)`;

      window.pageYOffset > 5
        ? (hiddenRef.current.style.display = 'none')
        : (hiddenRef.current.style.display = 'block');
    };

    window.addEventListener('scroll', handleScroll);

    return () => {
      window.removeEventListener('scroll', handleScroll);
      ref.current.style.transform = null;
    }
  }, []);

  return (
    <Container>
      <PreDisplay ref={hiddenRef} className='hidden'>
        <Anchor width={70} height={70} fill='currentColor' />
      </PreDisplay>
      <Slider ref={ref}>
        {[...Array(props.number)].map((x, id) => {
          return (
            <Link
              key={id}
              width={25}
              height={25}
              fill='currentColor'
              className='chain'
            />
          );
        })}
        <Anchor width={70} height={70} fill='currentColor' />
      </Slider>
    </Container>
  );
};

export default AnchorComponent;

enter image description here

I believe I am supposed to unmount the ref, however, when I do this it does not work. Please see below:

 return () => {
    window.removeEventListener('scroll', handleScroll);
    ref.current = null;
}

Anyone know what it could be? Thanks

about 4 years ago · Juan Pablo Isaza
1 Respuestas
Responde la pregunta

0

ref.current contains null on initialization. When ref.current.style.transform = 'translateY(${-diffP}%)'; is called inside useEffect , it tries to assign a value to a property inside an object, but there is no object, since it is null .

To fix it, you can try to initialize ref like so:.

 const ref = useRef({ style: { transform: null } })
about 4 years ago · Juan Pablo Isaza Denunciar
Responde la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Comercial
Legal
Términos y condiciones Política de privacidad
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomiéndame algunas ofertas
Necesito ayuda