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 Router
s 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 Route
s 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>
);
}
}
Related Topics
Random Numbers Between 1 and 50; 50 Times
Postman: How to Check Whether the Field Is Returning Null in the Postman Automation
Dynamically Change Background Color on Scroll
How to Add Node Module to Angular Project If Is Not Schematics Enabled
Changing the Value of Json Object's Key, Changes Other Values Also
How to Vertically and Horizontally Center a Component in React
React-Native: Application Has Not Been Registered Error
Read Lines of a Txt File and Organize in a Json File
How to Convert Gmt Time to Ist Time in JavaScript
How to Convert Raw Mp3 Binary into Blob Url and Play It in Audio Tag
Keep Selected Dropdown Result After Refreshing Page, Jquery
How to Hide Select Options With Javascript (Cross Browser)
Prevent React-Router History.Push from Reloading Current Route
Display Images in React Using Jsx Without Import
How to Clear Input After Onclick With Reactjs
Javascript on Click Event for Multiple Buttons With Same Class