Kumar
Kumar

Reputation: 59

How to navigate to a particular div on the same page in ReactJS?

I have to navigate to a particular div on the same page in React JS application. For example how it is being done in the following website. When one clicks on < NavLink > the UI scrolls and focuses on the particular div and similarly for other Links on this website. https://reacttraining.com/react-router/web/api/NavLink/strict-bool

Upvotes: 1

Views: 4182

Answers (2)

miki Palao Palmer
miki Palao Palmer

Reputation: 1

I think that maybe is a better aproach to use useRef hook. on click is almost the same:

const ref = useRef();

// the function when you want to scroll:
() => window.scrollTo({
    top: ref.current.offsetTop -100, 
    behavior: "smooth"
})

// Where you want to go
<div ref={ref} />

Upvotes: 0

divine
divine

Reputation: 4922

Get the offset of the target element and use window.scrollTo to position it either on top of the page or where ever you want. This would work in chrome/latest browsers. You might want to check for other browser compatibility.

let offsetTop  = document.getElementById("yourelement").offsetTop;
window.scrollTo({
    top: offsetTop-100, 
    behavior: "smooth"
});

Program is in codepen https://codepen.io/Divine1/pen/zbQVwR

Update

i have added this logic into a online reactjs project editor and it works. You can see how this code works https://repl.it/@Divine1/QuietHeartyApplicationstack

Check App.js App.css and the live result.

Upvotes: 2

Related Questions