Skip to content Skip to sidebar Skip to footer

Scroll To A Particular Div Using Id In Reactjs Without Using Any Other Library

Scroll to a particular div using id in react without using any other library, I found a few solutions they were using scroll libraries here's the div code in my WrappedQuestionFor

Solution 1:

I use a react ref and element.scrollIntoView to achieve this.

classAppextendsComponent {
  constructor(props) {
    super(props);
    this.scrollDiv = createRef();
  }

  render() {
    return (
      <divclassName="App"><h1>Hello CodeSandbox</h1><buttononClick={() => {
            this.scrollDiv.current.scrollIntoView({ behavior: 'smooth' });
          }}
        >
          click me!
        </button><h2>Start editing to see some magic happen!</h2><divref={this.scrollDiv}>hi</div></div>
    );
  }
}

Here's a sample codesandbox that demonstrates clicking a button and scrolling an element into view.

Solution 2:

Have you tried using Ref?

constructor(props) {
  super(props);
  this.myRef = React.createRef();
}

handleScrollToElement(event) {
  if (<some_logic>){
    window.scrollTo(0, this.myRef.current.offsetTop);
  }
}

render() {

  return (
    <div><divref={this.myRef}></div></div>)
}

Post a Comment for "Scroll To A Particular Div Using Id In Reactjs Without Using Any Other Library"