简体   繁体   中英

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

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.

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.current.offsetTop,
    behavior:"smooth"
`});
};

But this approach is not referred, instead use refs to fully levarage the benefits of react.

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" });
};

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM