React router dom v5 default route doesn't work - javascript

I'm using react router dom v5 with material ui, and I have my routes in the following way:
import React from 'react'
import { BrowserRouter, Route, Switch } from 'react-router-dom'
import Layout from '../components/layout'
import Login from '../screens/Login'
import NotFound from '../screens/NotFound'
import routes from './routes'
const DynamicRoutes = () => {
return (
<>
{Object.values(routes).map(({ component, path }) => (
<Route exact path={path} key={path} component={component} />
))}
</>
)
}
const Router = () => {
return (
<BrowserRouter>
<Switch>
<Route exact path="/login" component={Login} />
<Layout>
<DynamicRoutes />
</Layout>
<Route path="*" component={NotFound} />
</Switch>
</BrowserRouter>
)
}
export default Router
I have already tried with <Route component={NotFound} />, and neither worked to me. Can anyone help me? The rest of routes work correctly, but when I type a fake route, doesn't go to the NotFound screen.

That occurs because all children of a <Switch> should be <Route> or <Redirect> elements.
You can check more about it in react-router-dom docs.
So, one solution for your code would be do something like that:
<BrowserRouter>
<Switch>
<Route exact path="/login" component={Login} />
{Object.values(routes).map(({ Component, path }) => (
<Route exact path={path} key={path}>
<Layout>
<Component />
</Layout>
</Route>
))}
<Route path="*" component={NotFound} />
</Switch>
</BrowserRouter>
*For your routes object array, Component property must be with an upper C.
You can check this sample code.

Related

Dynamic routing will not display component

I am using react-router-dom v6, "react": "^18.2.0", and not able to render a Details component. This is my routing:
function Routing() {
return (
<BrowserRouter>
<Routes>
<Route path="/" element={<List />} />
<Route path="details/:id" element={<Details />} />
<Route path="other" element={<Other />} />
</Routes>
</BrowserRouter>
);
}
I am using this to try to access the Details component:
<Link to={'details' + `/${props.id}`}/>
The details component is as basic as this:
import react from 'React'
const Details = () => {
return (<h1>HELLO</h1>)
}
export default Details;
But the component will not render, and I am getting the warning "No routes matched location "/details/weI4qFO9/UW9v5WFllYhFw==""
It's only dynamic routing that will not render the component. Any idea what I am doing wrong or missing?
you are missing the / before details on the router and the link
function Routing() {
return (
<BrowserRouter>
<Routes>
<Route path="/" element={<List />} />
<Route path="/details/:id" element={<Details />} />
<Route path="/other" element={<Other />} />
</Routes>
</BrowserRouter>
);
}
<Link to={`/details/${props.id}`}/>

React Protected Route Not Working in My App.js --- v6 [duplicate]

This question already has answers here:
How to create a protected route with react-router-dom?
(5 answers)
Closed 4 months ago.
Help
I'm using a protected route in my React app. But it is not working. All the other Elements are working but when I got to "/account" the whole screen is white. This is my code. It will be really helpful for me if you give that answer. Thank You :)
Protected Route code:
import React, { Fragment } from 'react';
import { useSelector } from 'react-redux';
import { Route, Routes, redirect } from 'react-router-dom';
const ProtectedRoute = ({ element: Element, ...rest }) => {
const { loading, isAuthenticated, user } = useSelector(state => state.user);
return (
<Fragment>
{!loading &&
(<Routes>
<Route
{...rest}
render={(props) => {
if(!isAuthenticated) {
return redirect("/login")
}
return <Element {...props} />
}}
/>
</Routes>
)}
</Fragment>
)
}
export default ProtectedRoute;
I am using ProtectedRoute.js in App.js. Here is the code.
App.js Code:
import React from 'react';
import {BrowserRouter as Router,Route,Routes} from "react-router-dom";
import './App.css';
import Header from "./component/layout/Header/Header.js";
import webFont from "webfontloader";
import Footer from './component/layout/Footer/Footer';
import Home from "./component/Home/Home.js";
import ProductDetails from "./component/Product/ProductDetails.js";
import Products from "./component/Product/Products.js";
import Search from "./component/Product/Search.js";
import LoginSignUp from './component/User/LoginSignUp';
import store from "./store";
import { loadUser } from './action/userAction';
import UserOption from "./component/layout/Header/UserOption.js";
import { useSelector } from 'react-redux';
import Profile from "./component/User/Profile.js"
import ProtectedRoute from './component/Route/ProtectedRoute';
function App() {
const {isAuthenticated, user} = useSelector(state => state.user)
React.useEffect(() => {
webFont.load({
google:{
families:["Roboto","Droid Sans","Chilanka"]
},
});
store.dispatch(loadUser())
}, [])
return (
<Router>
<Header />
{isAuthenticated && <UserOption user={user} />}
<Routes>
<Route path="/" element={<Home />} />
<Route path="/product/:id" element={<ProductDetails />} />
<Route path="/products" element={<Products />} />
<Route path="/products/:keyword" element={<Products />} />
<Route path="/search" element={<Search />} />
<Route path="/account" element={ <ProtectedRoute> <Profile /> </ProtectedRoute> } />
<Route path="/login" element={<LoginSignUp />} />
</Routes>
<Footer />
</Router>
);
}
export default App;
In your App.js you can declare the protected route like this
<Route path="/account" element={ <ProtectedRoute /> } >
<Route path="/account" element={ <Profile /> } >
</Route>
You can use Outlet of react-router v6 for passing the Component
const ProtectedRoute = ({ element: Element, ...rest }) => {
const { loading, isAuthenticated, user } = useSelector(state => state.user);
if (loading) {
return <h2>Loading...</h2>
}
return isAuthenticated ? <Outlet /> : <Navigate to="/login" />;
}
# Sayedul Karim.
I have a better and more concise way for this, An example of the code is below.
<Routes>
<Route element={<App />}>
{isAuthenticated ? (
<>
<Route path="/*" element={<PrivateRoutes />} />
<Route
index
element={<Navigate to="/account" />}
/>
</>
) : (
<>
<Route path="auth/*" element={<AuthPage />} />
<Route path="*" element={<Navigate to="/auth" />} />
</>
)}
</Route>
</Routes>
In this way, you don't have to make any private component instead just make a component for private routes where the routes are defined.
The PrivateRoutes component will be like this
<Routes>
<Route>
{/* Redirect to account page after successful login */}
{/* Pages */}
<Route path="auth/*" element={<Navigate to="/account" />} />
<Route path="account" element={<Account />} />
</Routes>
If any query further, feel free to ask....
I'm not sure, but you haven't pass any "element" prop to your ProtectedRoute component. You pass Profile component as children, so try render children instead of element in ProtectedRoute if you want your code to work like this.
I believe that you might want not to nest those routes, so also you might want to try use ProtectedRoute as Route in your router, I'm talking about something like this
<Routes>
...
<ProtectedRoute path="/account" element={<Profile />} />
...
</Routes>
UPDATE
It might show you this error because your Route is conditionally rendered, so try to handle loading state in some other way, maybe something like this
return (
<Route
{...rest}
render={(props) => {
if(!isAuthenticated) {
return redirect("/login")
}
if(loading) {
return <LoadingComponent />
}
return <Element {...props} />
}}
/>
)

I'm getting blank react-app page on using Route

I'm having some kind of trouble when I'm using Router in App.js
I'm getting a blank page when I am using, I tried a lot but couldn't found a way to solve the issue.
<GuestRoute path="/Authenticate" element={<Authenticate />}>
</GuestRoute>
it is working fine with
<Route path="/Authenticate" element={<Authenticate />}>
</Route>
but I have to use GuestRoute.
Given below is the whole code:
App.js
import "./App.css";
import {BrowserRouter as Router, Routes, Route, Navigate } from "react-router-dom";
import React from "react"
import Navigation from "./components/shared/Navigation/Navigation";
import Home from "./Pages/Home/Home";
import Register from "./Pages/Register/Register";
import Login from "./Pages/Login/Login";
import Authenticate from "./Pages/Authenticate/Authenticate";
const isAuth = true;
function App() {
return (
<div className="App">
<Router>
<Navigation />
{/* switch(prev. versions) ----> Routes (new versions)) */}
<Routes>
<Route exact path="/" element={<Home />} >
</Route>
<GuestRoute path="/Authenticate" element={<Authenticate />}>
</GuestRoute>
</Routes>
</Router>
</div>
);
}
const GuestRoute = ({children,...rest}) => {
return(
<Route {...rest}
render={({location})=>{
return isAuth ? (
<Navigate to={{
pathname: '/rooms',
state: {from: location}
}}
/>
):(
children
);
}}
></Route>
);
};
export default App;
react-router-dom#6 doesn't use custom route components. The new pattern used in v6 are either wrapper components or layout route components.
Wrapper component example:
const GuestWrapper = ({ children }) => {
... guest route wrapper logic ...
return (
...
{children}
...
);
};
...
<Router>
<Navigation />
<Routes>
<Route path="/" element={<Home />} />
<Route
path="/Authenticate"
element={(
<GuestWrapper>
<Authenticate />
</GuestWrapper>
)}
/>
</Routes>
</Router>
Layout route component example:
import { Outlet } from 'react-router-dom';
const GuestLayout = () => {
... guest route wrapper logic ...
return (
...
<Outlet /> // <-- nested routes render here
...
);
};
...
<Router>
<Navigation />
<Routes>
<Route path="/" element={<Home />} />
<Route element={<GuestLayout>}>
<Route path="/Authenticate" element={<Authenticate />} />
... other GuestRoute routes ...
</Route>
</Routes>
</Router>

How to write/create a private route in react-router-dom v6?

I tried creating a private route using react-router-dom v6 as shown below in React JS
import React from 'react';
import {BrowserRouter as Router, Routes, Route} from 'react-router-dom';
import * as ROUTES from './constants/routes';
import { Home, Signin, Signup, Browse } from './pages';
import { IsUserRedirect, ProtectedUserRedirect } from './helpers/routes';
function App() {
const user=null;
return (
<>
<Router>
<Routes>
<Route exact path={ROUTES.HOME} element={<IsUserRedirect user={user} path={ROUTES.BROWSE} />}>
<Route element={<Home />} />
</Route>
<Route exact path={ROUTES.BROWSE} element={<ProtectedUserRedirect user={user} path={ROUTES.SIGN_IN} />}>
<Route element={<Browse />} />
</Route>
<Route exact path={ROUTES.SIGN_IN} element={<IsUserRedirect user={user} path={ROUTES.BROWSE} />}>
<Route element={<Signin />} />
</Route>
<Route exact path={ROUTES.SIGN_UP} element={<IsUserRedirect user={user} path={ROUTES.BROWSE} />}>
<Route element={<Signup />} />
</Route>
</Routes>
</Router>
</>
);
}
export default App;
and the helper components are implemented as shown below
import React from 'react';
import { Navigate, Outlet } from 'react-router-dom';
export const IsUserRedirect = ({path, user, children}) => {
console.log(Boolean(user))
return (
user?<Navigate to={path} replace />:<Outlet />
)
}
export const ProtectedUserRedirect = ({path, user, children}) => {
console.log(Boolean(user))
return (
user?<Outlet />:<Navigate to={path} replace />
)
}
NO ERROR AT TERMINAL AND CONSOLE but I'm not getting any output. The components seems to not rendering properly. Could you please me how to write better private route in v6 of router-dom. Reference: https://dev.to/iamandrewluca/private-route-in-react-router-v6-lg5
THANKS IN ADVANCE

Nested index route not rendering in react-router-dom v6

I have a create-react-app project with react-router-dom v6 installed. Trying to use the new index route syntax so that my HomePage component renders at the index that is currently serving a Layout component. When I navigate to the index (http://localhost:3000/), it renders the Layout component with site name in an but not the HomePage component (The "Home Page" does not render).
Thanks for the help!
Code below:
App.js
import './App.css';
import {Routes, Route, Outlet, Link, BrowserRouter as Router} from "react-router-dom";
import Layout from "./components/layout/Layout";
import HomePage from "./pages/Home";
function App() {
return (
<div className="App">
<Router>
<Routes>
<Route path="/" element={<Layout />}>
<Route index element={<HomePage />} />
</Route>
</Routes>
</Router>
<Outlet />
</div>
);
}
export default App;
Home.js
const HomePage = () => {
return (
<div>
<h1>Home Page</h1>
</div>
)
}
export default HomePage
Layout.js
import data from "../../config/siteconfig.json"
const settings = data.settings;
const Layout = ({children}) => {
return (
<div>
<h1>{settings.sitename}</h1>
{children}
</div>
)
}
export default Layout
If you want nested Route components to render then the Layout component should render an Outlet for them to be rendered into. Using children prop would be if Layout was directly wrapping children components.
In other words, it is the difference between
<Route
path="/"
element={(
<Layout>
<HomePage /> // <-- rendered as children
</Layout>
)}
/>
and
<Route path="/" element={<Layout />}>
<Route index element={<HomePage />} /> // <-- rendered as nested route
</Route>
Suggested code update:
import { Outlet } from 'react-router-dom';
const Layout = ({children}) => {
return (
<div>
<h1>{settings.sitename}</h1>
<Outlet />
</div>
);
};
...
function App() {
return (
<div className="App">
<Router>
<Routes>
<Route path="/" element={<Layout />}>
<Route index element={<HomePage />} />
</Route>
</Routes>
</Router>
</div>
);
}

Categories