Toyo U
Toyo U

Reputation: 61

React-router-dom Router not working. Jumps to 404 page only

I am working with react router on a small project. I initially had my AppRouter working with BrowserRouter and everything works fine. But I had to switch to Router so I could add my own history object. With Router my page navigations do not work, instead it jumps straight to my 404 page. Any suggestions on what I am doing wrong will be appreciated.

import React from "react";
import AddExpensePage from "../components/AddExpensePage";
import EditExpensePage from "../components/EditExpensePage";
import ExpenseDashboardPage from "../components/ExpenseDashboard";
import Header from "../components/Header";
import HelpPage from "../components/HelpPage";
import NotFoundPage from "../components/NotFoundPage";
import { createBrowserHistory } from "history";
import LoginPage from "../components/LoginPage";

import { Switch, BrowserRouter, Route, Router } from "react-router-dom";

export const history = createBrowserHistory();

const AppRouter = () => (
  <Router history={history}>
    <div>
      <Header />
      <Switch>
        <Route path="/" component={LoginPage} exact={true} />
        <Route path="/dashboard" component={ExpenseDashboardPage} />
        <Route path="/create" component={AddExpensePage} />
        <Route path="/edit/:id" component={EditExpensePage} />
        <Route path="/help" component={HelpPage} />
        <Route component={NotFoundPage} />
      </Switch>
    </div>
  </Router>
);

export default AppRouter;

Upvotes: 1

Views: 199

Answers (2)

Mosia Thabo
Mosia Thabo

Reputation: 4277

I would suggest that you keep using BrowserRouter. React Hooks now make using history possible despite the type of Router you're using.

From ReactRouter documentation, useHistory is there to your rescue:

The useHistory hook gives you access to the history instance that you may use to navigate.

To access the history object anywhere in your app inside the Routed Components, you can do the following inside of that component:

let history = useHistory();

Then you have access to history.push() and other methods you wish to call to fiddle with history.


Conclusion:

Don't switch to <Router>, keep using <BrowserRouter> and use hooks to access history using useHistory.

Upvotes: 1

PatrykBuniX
PatrykBuniX

Reputation: 152

You have to wrapp your routes with BrowserRouter component, for example:

const AppRouter = () => (
  <Router history={history}>
    <div>
      <Header />
      <BrowserRouter>
      <Switch>
        <Route path="/" component={LoginPage} exact={true} />
        <Route path="/dashboard" component={ExpenseDashboardPage} />
        <Route path="/create" component={AddExpensePage} />
        <Route path="/edit/:id" component={EditExpensePage} />
        <Route path="/help" component={HelpPage} />
        <Route component={NotFoundPage} />
      </Switch>
      </BrowserRouter>
    </div>
  </Router>
);

Upvotes: 1

Related Questions