I want to improve my scrolling code. I have the following working code…
const scrollRef = [];
const scrollClick = (event) => {
console.log(scrollRef[1]);
scrollRef[1].scrollIntoView();
}
The above works using…
<button onClick={scrollClick}>Bottom Of Page</button>
which scrolls to …
<div ref={(ref) => { scrollRef[1] = ref }}> Bottom of page </div>
What I want to do is call the particular reference point in the scrollRef[x] array from the button instead, for example…
<button onClick={scrollClick[1]}>Bottom Of Page </button>
>Solution :
To strictly answer your question following your current code and logic, you could do something such as the following:
const scrollClick = (index) => {
scrollRef[index].scrollIntoView();
}
With the button rendered with:
<button onClick={() => scrollClick(1)}>Bottom Of Page </button>
(Assuming scrollClick[1] is a typo) When passing onClick, you are passing a callback – if you pass a function call directly (i.e. myFunc(someValue) and not () => myFunc(someValue)) then myFunc will executed on render – the return value of it being set as the onClick handler.