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?