L3 Zhang
L3 Zhang

Reputation: 105

Js div scroll to bottom in React component

I have a problem by writing the function scrollToBot. The function would be called by componentDidMount and componentDidUpdate. But the div doesn't scroll. I don't know what's wrong in this function. Must I ues JQuery to implement this function?

Thanks in advance.

scrollToBot(){
    console.log(this.textAreaDiv.offsetHeight); // 4000
    if(this.textAreaDiv.offsetHeight>3000){
        console.log("should scoll!!!!!!!!!!!!!!"); // showed
        this.textAreaDiv.scrollTop=2000;
    }
    console.log('run scrollTo'); // showed
}

componentDidMount(){
    this.scrollToBot();
}

componentDidUpdate(){
    this.scrollToBot();
}

Upvotes: 0

Views: 656

Answers (2)

GibboK
GibboK

Reputation: 73988

In your JSX use ref in order to access the dom element from the rest of your react component.

Example:

...
textAreaDiv: null

setInputRef(dom){
    this.textAreaDiv = dom
}

render(){
    <div ref={this.setInputRef}/>
}

`

Upvotes: 1

Javed
Javed

Reputation: 470

This will not work in React, since it uses Virtual DOM, to access the real DOM elements you need to use Refs as described in React Documents

Upvotes: 1

Related Questions