How to get scroll properties in react-simplebar (in stateful function)

3.1k Views Asked by At

I am new with refs in react.js and in the react-simplebar documentation it just shows how to get the scroll ref for a stateless function.

class App extends React.Component {
  render() {
    console.log(this.refs.scroll)    // => Undefined
    return (
      <Simplebar ref={this.refs.scroll}><h1>scrollable element</h1></Simplebar>
    )
  }
}

2

There are 2 best solutions below

0
M Shahzaib Shoaib On BEST ANSWER

try this

class App extends React.Component {
constructor(props) {
        super(props);
        this.scrollableNodeRef = React.createRef();
    }
  
  onChangeScrollToTop() {
        this.scrollableNodeRef.current.scrollTop = 0;

    }
  
  
  render() {
    console.log(this.refs.scroll)    // => Undefined
    return (
      <Simplebar scrollableNodeProps={{ ref:this.scrollableNodeRef }}>
      <h1>scrollableelement</h1>
      </Simplebar>
    )
  }
}

0
Blademaster680 On

For anyone coming to this at a later date. This is how I managed to set the scrolling position after a few hours of digging around in a function component

const SimpleScrollerComponent = () => {
  // Create a reference for the SimpleBar component so we can acces it
  const scrollableNodeRef = React.createRef();

  const handleScrollDownBtnClicked = () => {
    // This is where we set the scroll position
    scrollableNodeRef.current.scrollTop = 1200;
  };

  return (
    <div>
      {/* We attach the reference to the component */}
      <SimpleBar scrollableNodeProps={{ ref: scrollableNodeRef }}>
        {/* This is where your code goes inside the scroll box */}
      </SimpleBar>

      <Button onClick={handleScrollDownBtnClicked}>Scroll to the Bottom</Button>
    </div>
  );
};