Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Referencing an object in an array by parsing it to the function

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 …

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

<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.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading