R. Kohlisch
R. Kohlisch

Reputation: 3003

ScrollIntoView in React without refs?

I have a big list of items / divs that I need to create programmatically, and I need to implement scrollIntoView buttons for each them. I know how to do it with refs.

Whether there is an alternative to refs that might be more performant?

Upvotes: 1

Views: 1072

Answers (1)

TKoL
TKoL

Reputation: 13932

I believe something like this will work:

onScrollClick(ev) {
    ev.target.scrollIntoView();
}

render() {
    return (
           ... <button onClick={this.onScrollClick}>Scroll This Element Into View</button>
      )
}

That assumes you want to scroll the button itself into view. If that's not what you want, you'll have to be specific.

[edit] if it's not the element itself, but one of the elements parents, you can also find a parent with javascript apis, element.parentElement -- you can use that as many times as you need to find the relevant element.

Upvotes: 1

Related Questions