How to show 404 Error Page in React Router V6 - javascript

I am using React for my webapp frontend . But during development , i came across routing problem in react-router-dom V6 . That problem is i would like to show 404 error page if none of the routes is matched . Here is my code ,
import React from 'react';
import { BrowserRouter,Routes,Route} from 'react-router-dom';
import Home from "./Pages/Home"
import Allposts from './Pages/Allposts'
import Createpost from './Pages/Createpost'
import Error404 from './Pages/Error404'
const App = () => {
return(
<>
<BrowserRouter>
<Routes>
<Route path="/" element={<Home />}/>
<Route path="/all-posts" element={<Allposts />}/>
<Route path="/create-post" element={<Createpost />} />
<Route path="*" element={<Error404 />} />
</Routes>
</BrowserRouter>
</>
)
}
export default App;
As you can see i have added catch all routes Route at the end with path equal to "*" mark . This catches all routes except the nested routes (and this is the problem ) . By general rule , it should catch all routes whether that is nested or not nested and it should display that 404 error page component . When i am using route "localhost:3000/all-posts/12345" <--- as this route is not present it should display that 404 error page component instead of showing this it shows a just blank page and an error pops out in console saying resource not found with an error of 404 that's it .
This is the problem . How to solve this problem and show 404 error page component .

Hi did you try ?
Try this
<Switch>
<Route path='*' component={Error404} />
</Switch>

react can't check on it's own if the post exists or not,
you can put a simple check like this to handle it
if (post exists) {
return <Post/>; //render Post info/details
} else {
return <Error404 />; // if not redirect to 404
}

If you could switch to this method, it would work for all the nested components as well.
import { createBrowserRouter, RouterProvider } from 'react-router-dom';
function Error404() {
return <h2>404 Not found</h2>;
}
const router = createBrowserRouter([
{
path: '/',
errorElement: <Error404 />,
children: [
{path: '', element: <Home /> },
{path: 'all-posts', element: <Allposts /> },
{path: 'create-post', element: <Createpost /> },
],
},
]);
function Router() {
return (
<RouterProvider router={router} />
);
}
export default Router;

Related

React page with sidebar component not rendering the component when clicked on link [duplicate]

I am having trouble writing code to render a login page with no navbar and sidebar. I have come across some pages that ask similar questions but none seem to pertain to my current situation.
How to hide navbar in login page in react router
the example given is great but I believe the way of accomplishing that same task has changed with react-router-dom v6 leading me to read about this change in https://dev.to/iamandrewluca/private-route-in-react-router-v6-lg5
It seems I am not understanding a certain aspect about routing with React Router. In the code below I have two Routes. One of the routes(Login) I would like to have render without the NavBar and SideBar component.
const App = () => {
return (
<>
<Routes>
<Route path="/login" element={<LoginPage />} />
</Routes>
<NavBar />
<SideBar />
<main className={styles["main--container"]}>
<div className={styles["main--content"]}>
<Routes>
<Route path="/" element={<Dashboard />} />
</Routes>
</div>
</main>
</>
);
};
An alternative, that I also tried, would be to move the NavBar and SideBar tags into the Dashboard component, but then I would essentially have to do the same copy and paste for any new components. This method felt wrong and inefficient , but if this is the correct way of doing it I will do the needful
Edit: I think it's important to include what it currently does is load the Login page with the NavBar and SideBar included. Navigating to the dashboard component has the NavBar and SideBar but this is intended.
What I would like is for the Login page not to have the NavBar and SideBar
If I understand your question, you are wanting to render the nav and sidebar on the non-login route. For this you can create a layout component that renders them and an outlet for the nested routes.
Using nested routes
import { Outlet } from 'react-router-dom';
const AppLayout = () => (
<>
<NavBar />
<SideBar />
<main className={styles["main--container"]}>
<div className={styles["main--content"]}>
<Outlet /> // <-- nested routes rendered here
</div>
</main>
</>
);
const App = () => {
return (
<>
<Routes>
<Route path="/login" element={<LoginPage />} />
<Route element={<AppLayout />} >
<Route path="/" element={<Dashboard />} /> // <-- nested routes
</Route>
</Routes>
</>
);
};
Using a routes configuration and useRoutes hook
const routesConfig = [
{
path: "/login",
element: <LoginPage />,
},
{
element: <AppLayout />,
children: [
{
path: "/",
element: <Dashboard />,
},
],
},
];
...
import { useRoutes } from 'react-router-dom';
const App = () => {
const routes = useRoutes(routesConfig);
return routes;
};
Using a routes configuration and data routers (introduced in v6.4.0)
const routesConfig = [
{
path: "/login",
element: <LoginPage />,
},
{
element: <AppLayout />,
children: [
{
path: "/",
element: <Dashboard />,
},
],
},
];
...
import { createBrowserRouter, RouterProvider } from 'react-router-dom';
const router = createBrowserRouter(routesConfig);
const App = () => {
return <RouterProvider router={router} />;
};
The easiest way for you to hide the navbar would be to go to the login page component and call useLocation(). Then you woulf do something like this after declaring the use location. And assigning it to a variable location
{ location.pathname === "/login" ? null : (
Render the whole navbar component);
Not sute if you can be able to read as I type from my phone

Route to an empty page does not work in a React app [duplicate]

I am having trouble writing code to render a login page with no navbar and sidebar. I have come across some pages that ask similar questions but none seem to pertain to my current situation.
How to hide navbar in login page in react router
the example given is great but I believe the way of accomplishing that same task has changed with react-router-dom v6 leading me to read about this change in https://dev.to/iamandrewluca/private-route-in-react-router-v6-lg5
It seems I am not understanding a certain aspect about routing with React Router. In the code below I have two Routes. One of the routes(Login) I would like to have render without the NavBar and SideBar component.
const App = () => {
return (
<>
<Routes>
<Route path="/login" element={<LoginPage />} />
</Routes>
<NavBar />
<SideBar />
<main className={styles["main--container"]}>
<div className={styles["main--content"]}>
<Routes>
<Route path="/" element={<Dashboard />} />
</Routes>
</div>
</main>
</>
);
};
An alternative, that I also tried, would be to move the NavBar and SideBar tags into the Dashboard component, but then I would essentially have to do the same copy and paste for any new components. This method felt wrong and inefficient , but if this is the correct way of doing it I will do the needful
Edit: I think it's important to include what it currently does is load the Login page with the NavBar and SideBar included. Navigating to the dashboard component has the NavBar and SideBar but this is intended.
What I would like is for the Login page not to have the NavBar and SideBar
If I understand your question, you are wanting to render the nav and sidebar on the non-login route. For this you can create a layout component that renders them and an outlet for the nested routes.
Using nested routes
import { Outlet } from 'react-router-dom';
const AppLayout = () => (
<>
<NavBar />
<SideBar />
<main className={styles["main--container"]}>
<div className={styles["main--content"]}>
<Outlet /> // <-- nested routes rendered here
</div>
</main>
</>
);
const App = () => {
return (
<>
<Routes>
<Route path="/login" element={<LoginPage />} />
<Route element={<AppLayout />} >
<Route path="/" element={<Dashboard />} /> // <-- nested routes
</Route>
</Routes>
</>
);
};
Using a routes configuration and useRoutes hook
const routesConfig = [
{
path: "/login",
element: <LoginPage />,
},
{
element: <AppLayout />,
children: [
{
path: "/",
element: <Dashboard />,
},
],
},
];
...
import { useRoutes } from 'react-router-dom';
const App = () => {
const routes = useRoutes(routesConfig);
return routes;
};
Using a routes configuration and data routers (introduced in v6.4.0)
const routesConfig = [
{
path: "/login",
element: <LoginPage />,
},
{
element: <AppLayout />,
children: [
{
path: "/",
element: <Dashboard />,
},
],
},
];
...
import { createBrowserRouter, RouterProvider } from 'react-router-dom';
const router = createBrowserRouter(routesConfig);
const App = () => {
return <RouterProvider router={router} />;
};
The easiest way for you to hide the navbar would be to go to the login page component and call useLocation(). Then you woulf do something like this after declaring the use location. And assigning it to a variable location
{ location.pathname === "/login" ? null : (
Render the whole navbar component);
Not sute if you can be able to read as I type from my phone

React router dom V6 hiding components/elements [duplicate]

I am having trouble writing code to render a login page with no navbar and sidebar. I have come across some pages that ask similar questions but none seem to pertain to my current situation.
How to hide navbar in login page in react router
the example given is great but I believe the way of accomplishing that same task has changed with react-router-dom v6 leading me to read about this change in https://dev.to/iamandrewluca/private-route-in-react-router-v6-lg5
It seems I am not understanding a certain aspect about routing with React Router. In the code below I have two Routes. One of the routes(Login) I would like to have render without the NavBar and SideBar component.
const App = () => {
return (
<>
<Routes>
<Route path="/login" element={<LoginPage />} />
</Routes>
<NavBar />
<SideBar />
<main className={styles["main--container"]}>
<div className={styles["main--content"]}>
<Routes>
<Route path="/" element={<Dashboard />} />
</Routes>
</div>
</main>
</>
);
};
An alternative, that I also tried, would be to move the NavBar and SideBar tags into the Dashboard component, but then I would essentially have to do the same copy and paste for any new components. This method felt wrong and inefficient , but if this is the correct way of doing it I will do the needful
Edit: I think it's important to include what it currently does is load the Login page with the NavBar and SideBar included. Navigating to the dashboard component has the NavBar and SideBar but this is intended.
What I would like is for the Login page not to have the NavBar and SideBar
If I understand your question, you are wanting to render the nav and sidebar on the non-login route. For this you can create a layout component that renders them and an outlet for the nested routes.
Using nested routes
import { Outlet } from 'react-router-dom';
const AppLayout = () => (
<>
<NavBar />
<SideBar />
<main className={styles["main--container"]}>
<div className={styles["main--content"]}>
<Outlet /> // <-- nested routes rendered here
</div>
</main>
</>
);
const App = () => {
return (
<>
<Routes>
<Route path="/login" element={<LoginPage />} />
<Route element={<AppLayout />} >
<Route path="/" element={<Dashboard />} /> // <-- nested routes
</Route>
</Routes>
</>
);
};
Using a routes configuration and useRoutes hook
const routesConfig = [
{
path: "/login",
element: <LoginPage />,
},
{
element: <AppLayout />,
children: [
{
path: "/",
element: <Dashboard />,
},
],
},
];
...
import { useRoutes } from 'react-router-dom';
const App = () => {
const routes = useRoutes(routesConfig);
return routes;
};
Using a routes configuration and data routers (introduced in v6.4.0)
const routesConfig = [
{
path: "/login",
element: <LoginPage />,
},
{
element: <AppLayout />,
children: [
{
path: "/",
element: <Dashboard />,
},
],
},
];
...
import { createBrowserRouter, RouterProvider } from 'react-router-dom';
const router = createBrowserRouter(routesConfig);
const App = () => {
return <RouterProvider router={router} />;
};
The easiest way for you to hide the navbar would be to go to the login page component and call useLocation(). Then you woulf do something like this after declaring the use location. And assigning it to a variable location
{ location.pathname === "/login" ? null : (
Render the whole navbar component);
Not sute if you can be able to read as I type from my phone

How do make my login page show first and then the navbar and everything else? [duplicate]

I am having trouble writing code to render a login page with no navbar and sidebar. I have come across some pages that ask similar questions but none seem to pertain to my current situation.
How to hide navbar in login page in react router
the example given is great but I believe the way of accomplishing that same task has changed with react-router-dom v6 leading me to read about this change in https://dev.to/iamandrewluca/private-route-in-react-router-v6-lg5
It seems I am not understanding a certain aspect about routing with React Router. In the code below I have two Routes. One of the routes(Login) I would like to have render without the NavBar and SideBar component.
const App = () => {
return (
<>
<Routes>
<Route path="/login" element={<LoginPage />} />
</Routes>
<NavBar />
<SideBar />
<main className={styles["main--container"]}>
<div className={styles["main--content"]}>
<Routes>
<Route path="/" element={<Dashboard />} />
</Routes>
</div>
</main>
</>
);
};
An alternative, that I also tried, would be to move the NavBar and SideBar tags into the Dashboard component, but then I would essentially have to do the same copy and paste for any new components. This method felt wrong and inefficient , but if this is the correct way of doing it I will do the needful
Edit: I think it's important to include what it currently does is load the Login page with the NavBar and SideBar included. Navigating to the dashboard component has the NavBar and SideBar but this is intended.
What I would like is for the Login page not to have the NavBar and SideBar
If I understand your question, you are wanting to render the nav and sidebar on the non-login route. For this you can create a layout component that renders them and an outlet for the nested routes.
Using nested routes
import { Outlet } from 'react-router-dom';
const AppLayout = () => (
<>
<NavBar />
<SideBar />
<main className={styles["main--container"]}>
<div className={styles["main--content"]}>
<Outlet /> // <-- nested routes rendered here
</div>
</main>
</>
);
const App = () => {
return (
<>
<Routes>
<Route path="/login" element={<LoginPage />} />
<Route element={<AppLayout />} >
<Route path="/" element={<Dashboard />} /> // <-- nested routes
</Route>
</Routes>
</>
);
};
Using a routes configuration and useRoutes hook
const routesConfig = [
{
path: "/login",
element: <LoginPage />,
},
{
element: <AppLayout />,
children: [
{
path: "/",
element: <Dashboard />,
},
],
},
];
...
import { useRoutes } from 'react-router-dom';
const App = () => {
const routes = useRoutes(routesConfig);
return routes;
};
Using a routes configuration and data routers (introduced in v6.4.0)
const routesConfig = [
{
path: "/login",
element: <LoginPage />,
},
{
element: <AppLayout />,
children: [
{
path: "/",
element: <Dashboard />,
},
],
},
];
...
import { createBrowserRouter, RouterProvider } from 'react-router-dom';
const router = createBrowserRouter(routesConfig);
const App = () => {
return <RouterProvider router={router} />;
};
The easiest way for you to hide the navbar would be to go to the login page component and call useLocation(). Then you woulf do something like this after declaring the use location. And assigning it to a variable location
{ location.pathname === "/login" ? null : (
Render the whole navbar component);
Not sute if you can be able to read as I type from my phone

Include collection of routes from another package in Router

Quick question here, I have the below code, and I want to be able to import a whole lot of routes from my package. The routes that are imported should be controlled by the package I'm building. If I add a new page in the package (say, ForgotPassword), then I won't want to come here and manually add an entry for ForgotPassword... It should just start working when I update to the latest version of the package.
Also, what will this route collection look like in my package project?
Any ideas welcome :D
...
import { RouteCollectionFromPackage } from "#my/package";
...
<Router basename="/">
<Suspense fallback={<div>Loading...</div>}>
<Switch>
{ /* I WANT TO IMPORT A COLLECTION OF ROUTES FROM MY PACKAGE */}
<RouteCollectionFromPackage />
{ /* THESE ARE IN MY APP */}
<Route exact path="/" component={home} />
<Route exact path="/search" component={search} />
</Switch>
</Suspense>
</Router>
Thanks!!
EDIT:
This is what I have tried, after following some of the suggestions below:
In my module:
const Routes = [
<Route exact path="/Login" component={Login} />,
<Route exact path="/ForgotPassword" component={Login} />,
<Route exact path="/MyProfile" component={Login} />
];
export { Routes };
In my consuming app:
import { Suspense, lazy } from "react";
import { HashRouter as Router, Switch, Route } from "react-router-dom";
import { Routes as PortalFrameworkRoutes, Login} from "#sal/portal";
const home = lazy(() => import("./pages/home/Home"));
const search = lazy(() => import("./pages/search/Search"));
function routes() {
return (
<Router basename="/">
<Suspense fallback={<div>Loading...</div>}>
<Switch>
{PortalFrameworkRoutes.map((route: Route) => route)}
<Route exact path="/" component={home} />
<Route exact path="/search" component={search} />
</Switch>
</Suspense>
</Router>
);
}
export default routes;
I get the error:
Error: Invariant failed: You should not use <Route> outside a <Router>
OR when I use {...PortalFrameworkRoutes} I get:
Spread children are not supported in React
EDIT #2:
This may actually be a crucial bit of information I omitted. In my module, the route is exported, and imported (and again exported) in an index.tsx like this:
export { Routes } from "./routes";
export { Login } from "./pages/login/Login";
I'm not sure if this is 100% correct, but it feels correct since I just want to do an import from the top level of my module, and have everything available there. i.e. import { Routes as PortalFrameworkRoutes, Login } from "#sal/portal";
In your package, export the routes like so:
const yourRoutes = [
<Route ... />,
<Route ... />,
];
export { yourRoutes };
Import it in your consuming application:
import { yourRoutes } from '#your/package';
Then use the array spread operator to include them along the other routes:
<Switch>
{...yourRoutes}
<Route path="/some/application/route" component=... />
</Switch>
In your "#my/package" module, you should export an Array of objects where each object has a path and component property which you can then dynamically render
Then in your current file, you can use the map method to render them
//"#my/package" module
//make sure to import the necessary components you will be adding
import component1 from "//..."
import component2 from "//..."
.
import componentN from "//..."
export myRoutes = [
{path: "/pathToComponent1", component: component1}
{path: "/pathToComponent2", component: component2}
.
{path: "/pathToComponentN", component: componentN}
]
// in your current module
import {myRoutes} from "#my/package"
<Router>
<switch>
...
// where you need to render routes from your module
{myRoutes.map(route => <Route path={route.path} component={route.component}/>}
...
</switch>
</Router>

Categories

Resources