ste
ste

Reputation: 3269

React-router-dom: Link cause the url to change but not the new component to load

I'm struggling to create nested route with React Router. I have build a small sample of what it doesn't work here:

https://codesandbox.io/s/silly-dubinsky-of2mu

Basically I have two routes with a sub-route each: first/first and second/first. In the FirstFirst component there's a link to the second route:

 <Link to="/second/first">go to second first</Link>

The problem is when clicking that link the url changes, but the correspondent component won't load. I can only see it after refreshing.

How can I fix this?

Upvotes: 1

Views: 248

Answers (2)

Zachary Haber
Zachary Haber

Reputation: 11037

You only need one Router component in your application

You also likely had infinite redirects due to the redirect being applied every render.

I removed the extra Router components, and then wrapped your First and Second components with a Switch component so that only one part of it would match. The Route would try to match, and if it failed, the redirect would occur.

https://codesandbox.io/s/trusting-wood-nbsg2?file=/src/Second.js

export default function Second() {
  return (
    <div>
      <Switch>
        <Route path="/second/first" component={SecondFirst} />
        <Redirect
          to={{
            pathname: "/second/first"
          }}
        />
      </Switch>
    </div>
  );
}

Upvotes: 1

user8737957
user8737957

Reputation:

I followed the link you shared, but it wasn't rendering anything on the browser. Anyways, I am guessing you are running this app on your local machine and using localhost:3000 or 127.0.0.1:3000 or any some another port.

If you configured your app with the localhost, make sure you use the localhost on the browser to view your app. If you use 127.0.0.1 as configuration, you should use this URL on the browser. I know they are both the local host and so on. But somehow it can cause the problem you are having, especially with server-side rendered apps.

Upvotes: 0

Related Questions