I am currently using react router dom for routing in my react application. I am trying to scroll to specific div on another page using Link from react router dom. The issue I am running into is that the page changes yet it does not scroll to the id of the div i have specified. I am unsure of what I am missing.
my code is as follows: App.js
import { Switch, Route, BrowserRouter as Router } from "react-router-dom";
import Home from "./Home";
import PageTwo from "./PageTwo";
import "./styles.css";
function App() {
return (
<Router>
<div className="App">
<Switch>
<Route exact path="/" component={Home} />
<Route path="/pagetwo" component={PageTwo} />
</Switch>
</div>
</Router>
);
}
export default App;
Home Page
import { Link } from "react-router-dom";
const Home = () => {
return (
<div>
<div>Navigate to div on new page</div>
<Link to="/pagetwo#div">Home</Link>
</div>
);
};
export default Home;
PageTwo:
const PageTwo = () => {
return (
<div>
<div style={{ marginTop: 500 }} id="div">
Page Two Div
</div>
</div>
);
};
export default PageTwo;
css:
html {
scroll-behavior: smooth;
}
attached is a code sandbox for debugging! https://codesandbox.io/s/silent-hill-0ln79?file=/src/PageTwo.js:0-171
As of this issue on github use react-router-hash-link package.
<HashLink to="/pagetwo#div">Home</HashLink>
here is the codesandbox
1. First install
npm i react-router-hash-link
or
npm i react-router-hash-link --force
2. Then import it and Provide the exact path and id of the component.
import { HashLink } from 'react-router-hash-link';
<HashLink to="/some/path#with-hash-fragment">Link to Hash Fragment</HashLink>
Note: For smmoth scroll add the following.
<HashLink smooth to="/path#hash">
Link to Hash Fragment
</HashLink>;
Help: react-router-hash-link
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With