user43712
user43712

Reputation: 187

React HashRouter - clicking links updates URL in browser but doesn't change page if link leads to page on same level

I have a website with a simple structure:

root
    branch
        leaf A
        leaf B

The routing is manage by HashRouter. <Link>s from branch -> leaf work fine, but from leaf -> leaf don't.

If I create a <Link> to leaf B on leaf A, then clicking it will update the URL in the browser and history, but the page won't update. Refreshing or opening in a new tab will cause the correct page to load though.

Here is the route I'm trying to follow, which works perfectly when the link is from a branch page: <Route exact path="/branch/:leaf" component={Leaf} />

When I create a link from one leaf page to another though, it doesn't work: <Link to={'/branch/' + name}>{name}</Link>

Any ideas what's going on here? Is HashRouter unable to link to a page on the same level of the route tree?

Upvotes: 0

Views: 1109

Answers (2)

user43712
user43712

Reputation: 187

Okay, I found a fix for this. And since I've searched for answers to other questions only to find a resolved thread that's years ago in which the OP (a deleted account, of course) just says 'nevermind, I figured it out', I'm writing it here.

The issue is with the fact that the leaf pages are all the same component, just with different props. When you click the link, the page updates but the component isn't redrawn. You have to tell React to redraw the component. The best way of doing this would be to change the props values on update and setState(). The lazy way (which works just fine for my use case) is to force a reload whenever the component is updated in any way. I did this by putting the following code method the leaf class:

  componentDidUpdate() {
    window.location.reload()
  }

Again, this isn't the prettiest fix. It works just fine for now though. Later on I will likely update the component properly and edit this post to reflect that. In the meantime hopefully this helps someone.

Upvotes: 0

TheWuif
TheWuif

Reputation: 1036

if you do something like this and you go to the path with the component isn't re-rendered. you have to listen on the params change if you want something to change.

may you post your leaf component to check where the error is?

the ugly fix would be something like this:

<Route exact path="/branch/:leaf" component={(props) => <Leaf {...props} key={window.location.pathname}/>}/>

Upvotes: 1

Related Questions