Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

React : setting scrollTop property of div doesn't work

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.

like image 946
anwesh mohapatra Avatar asked Nov 12 '18 15:11

anwesh mohapatra


2 Answers

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

like image 78
Sergiu Paraschiv Avatar answered Nov 15 '22 01:11

Sergiu Paraschiv


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/[email protected]/umd/react.production.min.js"></script>
<script src="https://unpkg.com/[email protected]/umd/react-dom.production.min.js"></script>

<div id="root"></div>
like image 45
Tholle Avatar answered Nov 15 '22 00:11

Tholle