2

I have a simple react app I'm working on that utilizes react router. My apps starts out of app.js and has the following router setup in app.js:

<BrowserRouter>
  <MuiThemeProvider theme={theme}>
    <NavigationBar onLogout={self.userLoggedOut} loggedIn={self.state.loggedIn} />
    <div className="content-area container-fluid">
      <Switch>
        <Route exact path="/" component={HomePage} />
        <Route exact path="/login" component={LoginPage} />
        <Route exact path="/page1" component={Page1} />
        <Route exact path="/page2" component={Page2} />
      </Switch>
    </div>
  </MuiThemeProvider>
</BrowserRouter>

In my app.js constructor, I have console.log to fire off a message to say the constructor was called. Initially I see the message fire off when first coming into the app and then if I use links to navigate between pages I do not see any follow up messages. However, if I go the browser address bar and type in a url manually (http://localhost:3000/login for example), the page loads successfully but have the message from the app.js constructor fire off again. How do you get a react/react-router app to accept manually entered urls the same as links so that the app doesn't reload?

Chris Dellinger
  • 2,292
  • 4
  • 25
  • 33

1 Answers1

1

In my app.js constructor, I have console.log to fire off a message to say the constructor was called. Initially I see the message fire off when first coming into the app and then if I use links to navigate between pages I do not see any follow up messages

This is the general behaviour of react app. Very first time you call the link the your app.js enters the tree and it gets rendered. While rendering all lifecycle method including constructor fires in fixed sequence so you are able to see log but when you are changing the link then the component corresponding to route inside is unmounted and component related to new route is rendered and not the complete app.js. This is why you do not see log again.

How do you get a react/react-router app to accept manually entered urls the same as links so that the app doesn't reload?

You cannot do so because when you are explicitly entering url in address bar then your browser doesnot relate the url with the running web application. It will always render your web application from the beginning. So when it is rendering from beginning you will always get that log.

  • Hmm, so what is the recommended way to maintain state if someone decides to suddenly manually enter a url? – Chris Dellinger Aug 01 '18 at 23:26
  • That totally depends on your use case, if you build redux state from very first page or you are consuming some state in the entered link and you don't find that either redirect to homepage or show some error page coz at once you cannot provide desired state to routes – Shubham Agarwal Bhewanewala Aug 02 '18 at 04:21