1

I am learning hooks and facing the following issue with ref object. When running this snippet:

  const [offset, setOffset] = useState(0);
  const [maxX, setMaxX] = useState(0);
  const itemRef = React.createRef();

  useEffect(() => {
    if (itemRef.current.childElementCount > 0) {
      setMaxX((itemRef.current.childElementCount / 3) * 
      itemRef.current.offsetWidth - itemRef.current.offsetWidth)
    }
  }, [])

  useEffect(() => {
    itemRef.current.style.transform = `translateX(-${offset}px)`
  }, [offset])

  const shiftSliderRight = () => {
    setOffset(offset => offset + itemRef.current.offsetWidth);
  }

  return (
    <div>
      <div className='page-new-arrivals'>
        <img src={'./static/arrivals_ss19.png'} alt='Arrivals'/>
        <div className='page-new-arrivals__slider_container'>
            <div ref={itemRef} className='page-new-arrivals__slider'>
            <Link to="/itemPage"><Item imgLink='./static/tshirt1.png'/></Link>
            <Item imgLink='./static/tshirt2.png'/>
            <Item imgLink='./static/tshirt3.png'/>

            <Item imgLink='./static/tshirt3.png'/>
            <Item imgLink='./static/tshirt1.png'/>
            <Item imgLink='./static/tshirt2.png'/>
          </div>
          <button onClick={shiftSliderRight}/>
        </div>
      </div>
    </div>
  )
}

I get Uncaught TypeError: Cannot read property 'style' of null of line itemRef.current.style.transform = `translateX(-${offset}px)

When I place the breakpoint on this line in goog dev tools, I see it is actually not null and all is fine, once finished rendering, no errors. Why is it so?

1

2 Answers 2

3

The line const itemRef = React.createRef(); creates a different ref object in each render... To use the same mutable ref:

const itemRef = useRef();
Sign up to request clarification or add additional context in comments.

Comments

1
// const itemRef = React.createRef();
const itemRef = useRef(null);

And you need to use if (itemRef.current) to determine whether the ref is initialized.

Docs: https://reactjs.org/docs/hooks-reference.html#useref

A good article: https://blog.bitsrc.io/react-useref-and-react-createref-the-difference-afedb9877d0f

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.