Search code examples
javascriptreactjsreact-router-dom

Scroll to a specific div on a new page using react router dom


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


Solution

  • As of this issue on github use react-router-hash-link package.

    <HashLink to="/pagetwo#div">Home</HashLink>
    

    here is the codesandbox