'React Router target div id in home page
I am using react router specifically the HashRouter since I am trying to host my react app on github pages. Prior to using the HashRouter I was just using the BrowserRouter and I was able to target a particular div on the default (Home) route (i.e. <Route exact path="/" component={Home} />)
by its id as follows ...
<li className="nav-item">
<a
className="nav-link text-white font-weight-bold"
href="/#about"
data-target="#about"
>
About
</a>
</li>
The above worked exactly as I had hoped by just scrolling the Home page down to the About section which had the id: #about. However, now I am using HashRouter and cannot achieve the same desired behaviour. Now when I click on the link it will just go to the Home component but will not scroll to the about section as it did before. Is there a simple solution to fix this? I have included snippets from the relevant code sections below...
<HashRouter basename="/">
<Switch>
<Route exact path="/" component={Home} />
<ContextProvider>
<Route
path="/terms-and-conditions"
component={TermsAndConditions}
/>
<Route path="/contact" component={Contact} />
<Switch>
<HashRouter>
<li className="nav-item">
<Link
className="nav-link text-white font-weight-bold"
to={{ pathname: "/", hash: "#about" }}
data-target="#about"
>
About
</Link>
Solution 1:[1]
Try this package React Router Hash Link. For more info on package, visit [react-router-hash-link] 1 but the steps below should suffice.
- Run
npm i react-router-hash-link
on your project. - Replace
<Link className="nav-link text-white font-weight-bold" to={{ pathname: "/", hash: "#about" }} data-target="#about"> About</Link>
- With
<HashLink to="/#about">About</HashLink>
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
Solution | Source |
---|---|
Solution 1 | STEPS |