6

I am new to react and currently I am trying to set the scrollTop property of a div to a desired number. Unfortunately, it doesn't work for me. See the code below:

class Testdiv extends React.Component {
  constructor(props){
    super(props);
    this.divRef = React.createRef();
  }
  componentDidMount(){
    this.divRef.current.scrollTop = 100;
  }
  render(){
    return (
     <div className="testDiv" ref={this.divRef}>
      Hello World<br /><br /><br /><br />
        Hello World!
      </div>
    );
  }
}
ReactDOM.render(
 <Testdiv />,
 document.getElementById('root')
);

And the CSS:

.testDiv{
  height: 500px;
  overflow: auto;
}

Here is the codeio pen for the respective code. P.S. I don't want to use Jquery. Thank you for the help.

anwesh mohapatra
  • 903
  • 4
  • 11
  • 19

2 Answers2

3

This is a css/overflow issue, not a JS/React one. The problem is that the testDiv is not high enough for anything to happen. Set height: 30px on it and you'll see the difference: https://codepen.io/anon/pen/ZmBydZ

Sergiu Paraschiv
  • 9,929
  • 5
  • 36
  • 47
1

You have to make sure that the content of testDiv is higher than the container itself and set the overflow on the y axis to scroll.

Example

class Testdiv extends React.Component {
  divRef = React.createRef();

  componentDidMount() {
    setTimeout(() => {
      this.divRef.current.scrollTop = 1000;
    }, 1000);
  }

  render() {
    return (
      <div style={{ height: 200, overflowY: "scroll" }} ref={this.divRef}>
        Hello World
        <div style={{ height: 300 }} />
        Hello World!
      </div>
    );
  }
}

ReactDOM.render(<Testdiv />, document.getElementById("root"));
<script src="https://unpkg.com/react@16.6.1/umd/react.production.min.js"></script>
<script src="https://unpkg.com/react-dom@16.6.1/umd/react-dom.production.min.js"></script>

<div id="root"></div>
Tholle
  • 108,070
  • 19
  • 198
  • 189
  • thank you, it's working. But I don't understand what you mean by "content of testDiv is higher than the container itself". Isn't testDiv the container? – anwesh mohapatra Nov 12 '18 at 15:29
  • @anweshmohapatra Great! The `testDiv` container in my example has a height of 200px, but the children of the `testDiv` container has a higher total height than that since one the the children is 300px in height. – Tholle Nov 12 '18 at 15:31