I’m trying to implement basic routing for my application but got stuck with the difference between the BrowserRouter and Router. In my case Router is working properly, BrowserRouter is not routing properly.
I’m using a history object.
When the user clicks a button, it needs to be taken to the login page
history.push('/login')
const Routing = () =>
<Router history={history}>
<Switch>
<Route exact path="/" component={Home} />
<Route path="/login" component={Login} />
</Switch>
</Router>
Above one work, but if I use BrowserRouter instead of Router it is not working properly.
BrowserRouter: BrowserRouter is a router implementation that uses the HTML5 history API(pushState, replaceState and the popstate event) to keep your UI in sync with the URL. It is the parent component that is used to store all of the other components.
Both BrowserRouter and HashRouter components were introduced in React Router ver. 4 as subclasses of Router class. Simply, BrowserRouter syncs the UI with the current URL in your browser, This is done by the means of HTML-5 History API. On the other hand, HashRouter uses the Hash part of your URL to sync.
They are technically three different packages: React Router, React Router DOM, and React Router Native. The primary difference between them lies in their usage. React Router DOM is for web applications and React Router Native is for mobile applications made with React Native.
On the basis of the part of URL that the router will use to track the content that the user is trying to view, React Router provides three different kinds of routers: Memory Router. Browser Router. Hash Router.
Simply, they are both to equal each other:
import { BrowserRouter } from 'react-router-dom'
<BrowserRouter>
<App />
</BrowserRouter>
and
import { Router } from 'react-router-dom'
import { createBrowserHistory } from 'history'
const history = createBrowserHistory()
<Router history={history}>
<App />
</Router>
<BrowserRouter>
is a <Router>
that uses the HTML5 history API
(pushState, replaceState and the popstate event) to keep your UI
in sync
with the URL.
So your routes should be like this,
const Routing = () => <BrowserRouter> <Switch> <Route exact path="/" component={Home} /> <Route path="/login" component={Login} /> </Switch> </BrowserRouter>
For navigation on click of a button you can use Redirect
from react-router-dom
package.
import { Redirect } from 'react-router-dom'
on click of button,
<Redirect to="/login" />
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With