1
votes

I'm running into something weird, and i'm not sure why it's happening. I'm using the HashRouter from React-Router-Dom because i'm trying to host my portfolio on Github Pages. When i link to a new page, the new page loads perfectly, but it seems to take me to the bottom of the new page, and not the top. Does anyone know why this might be happening?

app.js:

  <HashRouter>
        <div>
        <Navigation />
        <Switch>
        <Route exact path="/" component={Home} />
        <Route path="/About" component={About} />
        <Route path="/MyHumber" component={MyHumber} />
        <Route path="/Foragr" component={Foragr} />
        <Route path="/TheWatchlist" component={TheWatchlist} />
        </Switch>
        </div>
  </HashRouter>

link:

  <Col lg={6}>
    <h1 className="project-title">{this.state.title}</h1>
    <p>{this.state.description}</p>
      <Link to={this.state.path}>
        <Button>View Project</Button>
      </Link>
   </Col>
1
As I understand the problem is that when loading a new page, it instantly scrolls to the bottom? What does the url in the address bar look like after navigation? Is there som element at the bottom of the page that catches focus in a way? Any autofocus-forms or such? - jensmtg
it doesnt scroll, but the when i click the link, the new page is presented however its automatically at the bottom of the page. the url shows "localhost:3000/#/MyHumber" for example. No forms or anything. - juicy j
I see. If it's a matter of retaining scroll position from previous page this page from the documentation may help: reacttraining.com/react-router/web/guides/scroll-restoration. Otherwise, I can't see what's wrong from the code you have pasted. Are you perhaps able to recreate the problem in a code sandbox? - jensmtg

1 Answers

2
votes

Try:

import { createBrowserHistory } from 'history';

const history = createBrowserHistory();

history.listen(_ => {
  window.scrollTo(0, 0)  
});

in the HashRouter tag:

    <HashRouter history={history}>

    </HashRouter>

This worked for me.