1

For my ReactJS project I have a simple text list (using <ul> and <li> tags), which has it's own scroll bar to navigate through the list, but not the whole page. I was able to do this with this css code:

    #List-container {
        max-height: 425px;
        overflow: hidden;
        overflow-y: scroll;
    }

For my project, I need it to automatically scroll down to the bottom of the list. I tried using window.scrollTo()but it's not working, which I'm pretty sure is because of the fact that there is a secondary scroll bar.

Does anyone know how I could use window.ScrollTo(), or know any alternatives?

Thanks in advance!

2
  • it should be window.scrollTo not ScrollTo Commented May 8, 2018 at 8:02
  • Thanks, but I tried it again and it didn't work Commented May 8, 2018 at 8:06

2 Answers 2

1

I tried your code and I'm getting a scrollbar like it's supposed to.

To get something to automatically scroll to bottom I would do something like:

let wHeight = window.innerHeight;
window.scrollY = wHeight;

This is the simplest way I can think of to scroll to the bottom of the page. You can replace window with whatever you want to select in the DOM.

To instead scroll to the bottom of your list simply write:

let divHeight = document.getElementById('List-container');
window.scrollY = divHeight.offsetHeight;
Sign up to request clarification or add additional context in comments.

3 Comments

Is there a more "Reactjs-ly" alternative to .getElementByID? It might just be me, but I feel .getElementByID doesn't really fit with ReactJS
There is, but I can't say if it's better or worse. getElementById is as close to the DOM as you can get when selecting an element. But with React you have "refs" where you can set for example <div ref="myReactDiv"> and you can later select this with this.refs.myReactDiv. Hope this helps!
Isn't window.scrollY just a read-only property? How can you modify it?
1

You need to get reference for the ListContainer and then set scrollTop on it like

<ListContainer ref={ref => this.listContainer = ref} />

and use it like

const container = ReactDOM.findDOMNode(this.listContainer);
container.scrollTop = "125px"

9 Comments

On the top line what does this.listContainer represent?
Its a ref to the ListContainer component, check this for more details stackoverflow.com/questions/38093760/…
So if I wanted to I could change this.listContainer to what ever name I want - as it's being defined in that line? Am I right?
@Ben10, you can give whatever name you want.
Sorry for asking so many questions, but it's still not working. Am I setting the const container in the wrong part of the reactjs lifecycle or does it not matter?'
|

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.