React Router Not Working After the Page Refresh

React routes not working until page refresh

It is not working because Navbar is outside BrowserRouter. Move BrowserRouter in your App component and Remove Router from Navbar:

 return (

<Container maxwidh='lg'>
<BrowserRouter>
<Navbar />
<Grow in>
<Container>
<div className="content">
<Switch>
<Route path="/" exact component={Home} />
<Route path="/form" exact component={Form} />
<Route path="/auth" exact component={Auth} />
</Switch>
</div>
</Container>
</Grow>
</BrowserRouter>
</Container>

);

React Router not working after the page refresh

Seems like the issue was caused because the main App component was rendering before the routes are checked with if statement.

I then changed the logic of how I push routes - instead of using different switches, I left only one switch with all the routes. And inside the Login and Home components, I do the check (if authenticated) and use history.push() to redirect.

Thus, the problem was not with the router, but with the processes sequence after all.

Thank you all for your answers.

React Router works only after refreshing the page

Right, you've extraneous Routers declared, your header component has one. Remove this Router.

It is because each Router provides a routing context, and each component subscribing to a routing context gets the context from the closest router. The router providing context to the header wasn't rendering any routes so that is why the URL would change but the router actually rendering the Routes wasn't being notified that it should render a different path.

class Header extends Component {
constructor(props) {
...
}

...

render() {
return (
<React.Fragment>
{/* <Router> */} // <-- Remove this Router Component
<Navbar dark expand="md">
...
</Navbar>
<Modal isOpen={this.state.isModalOpen} toggle={this.toggleModal}>
...
</Modal>
{/* </Router> */}
</React.Fragment>
);
}
}

Edit react-router-works-only-after-refreshing-the-page



Related Topics



Leave a reply



Submit