Home > Mobile >  How can I jump to a div with a specific id in react
How can I jump to a div with a specific id in react

Time:06-09

I have a function that checks if a id string provided in the url pathname exists on the page and if it does I want to jump to that div on the page. I've been able to check if the id exists, but I can't find a way to jump to the id from a function in react. I tried using react-router-hash-link, but I can't see a way to make this work, I also tried this...

const navigate = useNavigate()

const func = id_string => { 
  navigate('#'   id_string)
}

This didn't jump to the relevant div like I'd hoped it would, anyone have any ideas how to make this work?

CodePudding user response:

You could do this using plain javascript

const func = id_string => { 
 document.querySelector(`#${id_string}`).scrollIntoView()
}

you can do this in useEffect actually, so you scroll right after the page has loaded

useEffect(() => {
  // get id from URL
  const id = ....

  document.querySelector(`#${id}`).scrollIntoView()
}, [])

CodePudding user response:

// method to jump to the desired element by using the element's id
const jumpToReleventDiv = (id) => {
  const releventDiv = document.getElementById(id);
  // behavior: "smooth" parameter for smooth movement
  releventDiv.scrollIntoView({behavior: "smooth"});
}

Read about scrollIntoView method here.

  • Related