Given the following code:
const AutoScrollToToday = (el)=>{
var a = moment(+moment().year()+"-01-01");
var b = moment();
const todaysPosition = b.diff(a,"days");
const result = todaysPosition * parseFloat(getComputedStyle(document.documentElement).fontSize);
el.scrollTo({left:result,top:0,behavior:'smooth'});
}
useEffect(() => {
const el = document.getElementById("visorVMainDiv");
AutoScrollToToday(el);
}, []);
My intention is that the element autoscroll once it is rendered (it is a calendar-like x-axys long component) and following information on the internet, using useEffect with an empty array should execute code once the component is rendered. However, I get the error Cannot read properties of null (reading 'scrollTo')
as the component hasn't been renderer yet. At this point I don't know to to proceed.
MODIFICATION----------(for comment suggestion, not working).
const AutoScrollToToday = (el)=>{
var a = moment(+moment().year()+"-01-01");
var b = moment();
const todaysPosition = b.diff(a,"days");
const result = todaysPosition * parseFloat(getComputedStyle(document.documentElement).fontSize);
el.scrollTo({left:result,top:0,behavior:'smooth'});
}
useEffect(() => {
visorVMainDiv !==null && AutoScrollToToday(visorVMainDiv.current);
}, [visorVMainDiv]);