Scroll to particular Item using ID of that item in react?

Viewed 9860

I was Trying to scroll to particular row item in react using ID of that item. I have the ID of particular row but not able to move there.

goToViolation=(id)=>{
  const violation = id ; 
  window.scrollTo({
    top:violation.current.offsetTop,
    behavior:"smooth"});
};

 if (isDrillDown) {
        isRowSelected = index === rowIndex % 20;
       if(isRowSelected){
        this.goToViolation(row.id);
       }
      }
  1. i was getting the ID from this Condition and i am passing it to the above function and using scrollTo function.
2 Answers

In order to scroll to an element you need ref for that element.

<div onClick={this.goToViolation("row-id")} id="row-id"></div>

Then in your function

goToViolation=(id)=>{
  const violation = document.getElementById(id); 
  window.scrollTo({
    top:violation.offsetTop,
    behavior:"smooth"
});
};

I agree with @MuhammadAsad that manipulating the DOM directly is not a React way.

Instead you can use useRef hook and pass the ref to your JSX element.

After that, you can collect the DOM reference from .current property.

Then you can just do

**your ref**.current.scrollIntoView({ behavior: "smooth", block: "start" });

Example,

Your variable declaration.

const violationRef = useRef(null);

Your JSX element which you want to scroll to.

<div ref={violationRef} ></div>

Your button which will bind onClick event.

<button onClick={goToViolation} />

Your handler function

const goToViolation=(id)=>{
  violationRef.current.scrollIntoView({ behavior: "smooth", block: "end" });
};
Related