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

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;

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.

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>
);

Related

Why unable to use protectRoute inside Router in react?

I have a react application in which users can access the homepage only after login/signup.
I have used protectRoutes to implement this , however I m getting the following error inside Router component:
A <Route> is only ever to be used as the child of <Routes> element, never rendered directly. Please wrap your <Route> in a <Routes>.
The code for app.js file:
import {useState} from 'react'
import './App.css';
import {Routes,Route,Link} from 'react-router-dom'
import SignupPage from './Pages/SignupPage';
import LoginPage from './Pages/LoginPage';
import Homepage from './Pages/Homepage';
import PrivateRoute from "./Pages/PrivateRoute";
import {HashRouter as Router} from 'react-router-dom'
function App() {
const [username,setUsername]=useState("");
const [currentUser,setCurrentUser]=useState({});
return (
<Router>
<div className="App">
<Route path="/" exact element={<SignupPage></SignupPage>}/>
<Route path="/signup" exact element={<SignupPage currentuser={currentUser} setcurrentuser={setCurrentUser} setusername={setUsername}></SignupPage>}/>
<Route path="/login" exact element={<LoginPage></LoginPage>}/>
<PrivateRoute path="/homepage" exact currentuser={currentUser} element={<Homepage user={currentUser} username={username} setusername={setUsername}></Homepage>}/>
</div>
</Router>
);
}
export default App;
Whats the error here and how do I fix it?
Issue
You are rendering Route components directly and are not wrapping them in a Routes component.
Solution
Refactor the PrivateRoute component to render an Outlet component instead of a Route and wrap the routes you want to protect.
Example:
import { Navigate, Outlet } from 'react-router-dom';
const PrivateRoute = ({ currentuser }) => {
// auth business logic
return isAuthenticated
? <Outlet />
: <Navigate to="/login" replace />;
};
...
import { HashRouter as Router, Routes, Route, Link} from 'react-router-dom'
function App() {
const [username,setUsername]=useState("");
const [currentUser,setCurrentUser]=useState({});
return (
<Router>
<div className="App">
<Routes>
... unprotected routes ...
<Route path="/" element={<SignupPage />} />
<Route
path="/signup"
element={(
<SignupPage
currentuser={currentUser}
setcurrentuser={setCurrentUser}
setusername={setUsername}
/>
)}
/>
<Route path="/login" element={<LoginPage />} />
...
<Route element={<PrivateRoute currentuser={currentUser} />}>
... protected routes ...
<Route
path="/homepage"
element={(
<Homepage
user={currentUser}
username={username}
setusername={setUsername}
/>
)}
/>
...
</Route>
</Routes>
</div>
</Router>
);
}

ReactJS Route function isn't working for me

I started learning ReactJS yesterday using Academind's crash course for beginners on it. There is a part where he teaches about react-router-dom. I tried using it on App.js and index.js as such:
App.js:
import { Route } from "react-router-dom";
import AllMeetupsPage from "./pages/AllMeetups";
import FavouritesPage from "./pages/Favourites";
import NewMeetupsPage from "./pages/NewMeetups";
function App() {
return (
<div>
<Route path='/'>
<AllMeetupsPage />
</Route>
<Route path='/favourites'>
<FavouritesPage />
</Route>
<Route path='/new-meetups'>
<NewMeetupsPage />
</Route>
</div>
);
}
export default App;
index.js:
import React from 'react';
import ReactDOM from 'react-dom';
import { BrowserRouter } from 'react-router-dom'
import './index.css';
import App from './App';
ReactDOM.render(
<BrowserRouter>
<App />
</BrowserRouter>,
document.getElementById('root')
);
There shouldn't be any error since I have fixed the syntax and imported the right files given in the video. Yet, in localhost:3000 I get this as the result.
If I just use <AllMeetupsPage /> then it works. If I put it in the route function then it doesn't. How can I fix this?
When you are just using <AllMeetupsPage/> then it's directly rendering that page component in App.js.
It's actually not doing any routing.
To use multiple you also need to wrap it within .
<div>
<Routes>
<Route path="/" element={<AllMeetupsPage />} />
<Route path="/favourites" element={<FavouritesPage />} />
<Route path="/new-meetups" element={<NewMeetupsPage />} />
</Routes>
</div>
You can refer to the following link to get more context of the problem:
[1]: ReactJS: [Home] is not a <Route> component. All component children of <Routes> must be a <Route> or <React.Fragment>
tyr this
import {Routes} from "react-router-dom"
<Routes>
<Route path='/'>
<AllMeetupsPage />
</Route>
<Route path='/favourites'>
<FavouritesPage />
</Route>
<Route path='/new-meetups'>
<NewMeetupsPage />
</Route>
</Routes>

Why my components don't display on my React page?

So I'm learning React and building an app with multiple pages, I made a Routes file which looks like this:
import 'swiper/swiper.min.css';
import React from "react";
import { Route, Routes } from "react-router-dom";
import Home from "../pages/Home";
import Catalog from "../pages/Catalog";
import Detail from "../pages/Detail";
const Router = () => {
return (
<Routes>
<Route
path='/:category/search/:keyword'
component={Catalog}
/>
<Route
path='/:category/:id'
component={Detail}
/>
<Route
path='/:category'
component={Catalog}
/>
<Route
path='/'
exact
component={Home}
/>
</Routes>
);
}
And App.js looks like this:
import { BrowserRouter, Route, Routes } from 'react-router-dom';
import Header from './components/header/Header';
import Footer from './components/footer/Footer';
import Router from './config/Router';
function App() {
return (
<BrowserRouter>
<Routes>
<Route render={props =>{
<>
<Header {...props}/>
<Router/>
<Footer/>
</>
}}/>
</Routes>
</BrowserRouter>
);
}
export default App;
As you see, I have a browser router and Route which passes props to a component(as I understood) but for some reason the components don't display on the page(original components just have with their name inside of them, but they don't display in App.js).
And my console also says:
No routes matched location "/"
In routes.jsx file. I'm guessing it should lead to main page, but for some reason the route doesn't match and components in App.js don't display.
In Version 6.0.0 there is not any component prop in Route. It has been changed to element. So you need to change your Router to :
const Router = () => {
return (
<Routes>
<Route
path='/:category/search/:keyword'
element={Catalog}
/>
<Route
path='/:category/:id'
element={Detail}
/>
<Route
path='/:category'
element={Catalog}
/>
<Route
path='/'
exact
element={Home}
/>
</Routes>
);
}
As you've said you're using react-router-dom 6.0.2, and it seems that the tutorial you are following is for the older version (5?). There were some breaking changes in version 6.
You need to change your Router component to use element instead of component:
const Router = () => {
return (
<Routes>
<Route path="/:category/search/:keyword" element={<Catalog />} />
<Route path="/:category/:id" element={<Detail />} />
<Route path="/:category" element={<Catalog />} />
<Route path="/" exact element={<Home />} />
</Routes>
);
};
and also your App component seems to be getting in the way with the nested route.
I think it can be simplified to:
function App() {
return (
<BrowserRouter>
<>
<Header />
<Router />
<Footer />
</>
</BrowserRouter>
);
}
You can see a working demo on stackblitz

React Router Switch not rendering specific component

I have a React app that is currently using react-router#4.2.0 and I'm struggling with rendering a specific component when the URL changes.
When I try to visit /locations/new it returns with a PropTypes error from the CityList component. I have tried adding in exact to the Route component within LocationsWrapper and then Main config too, however, this then influences other routes - such as /locations to become null.
// BrowserRouter
import React from "react";
import { render } from "react-dom";
import { BrowserRouter } from "react-router-dom";
import { Provider } from "react-redux";
import store from "./store";
import Navbar from "./components/Core/Navbar";
import Routes from "./config/routes";
render(
<Provider store={store}>
<BrowserRouter>
<div style={{ backgroundColor: "#FCFCFC" }}>
<Navbar />
<Routes />
</div>
</BrowserRouter>
</Provider>,
document.getElementById("root")
);
// Router config - ( Routes )
import React from "react";
import { Route, Switch } from "react-router-dom";
import Home from "../components/Home";
import Locations from "../components/Locations";
import CityList from "../components/CityList";
import CreateLocation from "../components/CreateLocation";
import Locale from "../components/Locale/index";
import Profile from "../components/Profile";
import NoMatch from "../components/Core/NoMatch";
import requireAuth from "../components/Core/HOC/Auth";
const LocationsWrapper = () => (
<div>
<Route exact path="/locations" component={Locations} />
<Route path="/locations/new" component={CreateLocation} />
<Route path="/locations/:id" component={CityList} />
</div>
);
const Main = () => (
<main>
<Switch>
<Route exact path="/" component={requireAuth(Home)} />
<Route path="/locations" component={LocationsWrapper} />
<Route path="/locale/:id" component={Locale} />
<Route path="/profile" component={requireAuth(Profile, true)} />
<Route component={NoMatch} />
</Switch>
</main>
);
export default Main;
Am I best avoiding <Switch> entirely and implementing a new method for routes that are undefined - such as 404s?
Yes, this will definitely return first
<Route path="/locations/:id" component={CityList} />
In react-router 4 there is no concept of index route, it will check each and every routes so in your defining routes are same
<Route path="/locations/new" component={CreateLocation} />
<Route path="/locations/:id" component={CityList} />
both path are same '/location/new' and '/location/:id' so /new and /:id are same params.
so at last 'CityList' will return
You can define like this
<Route path="/locations/create/new" component={CreateLocation} />
<Route path="/locations/list/:id" component={CityList} />
Pretty sure your route is not working cause you are also matching params with /locations/new with /locations/:id so then 'new' becomes Id param.
Try changing this
<Route path="/locations/new" component={CreateLocation} />
To something like this
<Route path="/locs/new" component={CreateLocation} />
Just a suggestion hope this may help

react-router is not rendering anything

I created my app with create-react-app and trying to use react-router on it. but it's not working at all.
Here's my Header.js.
import React, { Component } from 'react';
class Header extends Component {
render() {
return (
<nav>
<div className="nav-wrapper blue darken-1">
<a className="brand-logo center">Testing</a>
<div className="right">
<ul>
<li>
<a><i className="material-icons">vpn_key</i></a>
</li>
<li>
<a><i className="material-icons">lock_open</i></a>
</li>
</ul>
</div>
</div>
</nav>
);
}
}
export default Header;
my App.js.
import React, { Component } from 'react';
import Header from './Header';
class App extends Component {
render() {
return (
<div className="App">
<div className="Header">
<Header />
{this.props.children}
</div>
</div>
);
}
};
export default App;
and my index.js here.
import React from 'react';
import ReactDOM from 'react-dom';
import { Router, Route, browserHistory, IndexRoute } from 'react-router';
import App from './App';
import Home from './Home';
import Login from './Login';
import Register from './Register';
ReactDOM.render((
<Router history={browserHistory}>
<Route path="/" component={App}>
<IndexRoute component={Home}/>
<Route path="/home" component={Home}/>
<Route path="/login" component={Login}/>
<Route path="/register" component={Register}/>
</Route>
</Router>),
document.getElementById('root')
);
Don't worry about Home, Login, Register thing on index.js. They are super fine.
Am I doing something wrong?
Ho if you're v4* of react-router it won't work that way you should install react-router-dom and import it.
That's the way I did it
import {BrowserRouter, Route} from 'react-router-dom';
//modified code of yours
ReactDOM.render((
<BrowserRouter>
<div>
<Route path="/" component={App}>
<IndexRoute component={Home}/>
<Route path="/home" component={Home}/>
<Route path="/login" component={Login}/>
<Route path="/register" component={Register}/>
</Route>
</div>
</BrowserRouter>),
document.getElementById('root'));
Note: Don't forget to wrap the route in a wrapper or it'll throw an error!
and to set 404 page just provide another route without any path to it.If no routes found it will be rendered.
<Route component={FourOhFour} /> /* FourOhFour component as 404*/
** Bonus point
If you're new to react-router you may fall in a problem of rendering multiple routes at the same time. But you want to render only one route at a time. at this point.
/*Import Switch also*/
import {BrowserRouter, Route, Switch} from 'react-router-dom';
Then
/*Wrap your route with `Switch` component*/
<BrowserRouter>
<div>
<Switch>
<IndexRoute component={Home}/>
<Route path="/" component={App}/>
<Route path="/home" component={Home}/>
<Route path="/login" component={Login}/>
<Route path="/register" component={Register}/>
</Switch>
</div>
</BrowserRouter>
If you are using React Router 4, as said by other comments, you have to use 'react-router-dom' in order to import it in your component.
import { BrowserRouter as Router } from 'react-router-dom'
you can now give any component as a children of Router (it has to be a single node).
The main difference from the normal RR2-3 is that now every route is a simple component, and you can put it along with other components.
You don't have IndexRoute anymore, you just put the routes in the order you want:
<div>
<Header />
<Route path="/blabla/:bla" component={SingleBlaBla} />
<Route path="/aboutUs" exact component={AboutUs} />
<Route path="/" exact component={Home} />
<Footer />
</div>
there are more than a couple of things to understand, in the options of Route, the use of Switch, Redirect and other very useful components. Try to spend some time on some good documentation since it is a very good version, and it will stick around for a while.
If you can have a look at this wonderful introduction: https://egghead.io/courses/add-routing-to-react-apps-using-react-router-v4
and the doc website: https://reacttraining.com/react-router/
The correct format is
import React from 'react';
import { BrowserRouter as Router, Routes, Route, } from "react-
router-dom";
import './App.css';
import Home from './components/Pages/Home';
function App() {
return (
<>
<Router>
<Routes>
<Route exact path='/' element={<Home/>}/>
</Routes>
</Router>
</>
)}
export default App;
May not be your case but this could help someone else. In my case none of it worked. Turned out to be a case with parcel cache. Delete the parcel cache folder and ran npm run dev again and it worked.

Categories

Resources