0

I've got a page with a table generated by a class component where, depending on some logic, I have only one of its rows "active" in a certain moment. I'm trying to scroll to the "active" row as the user opens the page.

I've already read this discussion but it didn't help ReactJS how to scroll to an element

Doing like this I get that this.scrollHere.current is null

constructor(props) {
  super(props);
  this.scrollHere = React.createRef();
}

componentDidMount() {
  // not using 'current', scrollIntoView() results not to be a function
  this.scrollHere.current.scrollIntoView({behavior: 'smooth', block: 'start'})
}

render() {
  return(
    ...
    <tr ref={this.scrollHere}><td>...</td></tr>
    ...
  )
}

Is that because the reference, when componentDidMount() is called, doesn't yet exist? If so, how to make it work?

Luigi Caradonna
  • 1,044
  • 2
  • 12
  • 33
  • See this: https://stackoverflow.com/questions/51689653/how-to-smoothly-scroll-to-an-element-in-pure-javascript and just take ref to element to make it working - it's all the same. – Zydnar Aug 24 '19 at 15:02

1 Answers1

0

We can do something like this (use scrollIntoView), this issue with your code is that you are not using callback refs-:

it should be defined like this -:

    <tr ref={e => this.scrollHere = e}><td>....</td></tr>

    this.scrollHere.scrollIntoView()

Here is a working demo https://stackblitz.com/edit/react-yzszzv

also replace this.scrollHere.current.scrollIntoView({behavior: 'smooth', block: 'start'})

with this.scrollHere.scrollIntoView({behavior: 'smooth', block: 'start'})

Abhisar Tripathi
  • 1,569
  • 10
  • 21
  • Yes, with the button it works, but I want to scroll automatically as the page renders on the browser, but if I write the code inside the `componentDidMount()` function I get that the reference is `NULL`, like it is not yet ready at that point, same if I give an id to the element and then use jQuery inside the lifecycle function, the element is `NULL`. Can you build an example with the page which scrolls by itself as it shows up? Also if it shows up already scrolled would be fine. – Luigi Caradonna Aug 24 '19 at 15:31
  • Yeah sure check the link now... https://stackblitz.com/edit/react-yzszzv – Abhisar Tripathi Aug 24 '19 at 15:33
  • Does that help ??? Also you need to change `this.scrollHere.current.scrollIntoView({behavior: 'smooth', block: 'start'})` with `this.scrollHere.scrollIntoView({behavior: 'smooth', block: 'start'})` – Abhisar Tripathi Aug 24 '19 at 15:36