The following code (codesandbox) produces this warning when the root url is navigated to:
You rendered descendant (or called useRoutes()) at "/" (under <Route path="">) but the parent route path has no trailing "*"...
However, no warning is issued if I navigate to "/post/blah".
import { Routes, Route} from "react-router-dom";
const StreamPage = () => (
<>
<Routes>
<Route index element={<div /> } />
<Route path="post/:subslug/*" element={<div /> }/>
</Routes>
<Routes>
<Route index element={<div />} />
<Route path="post/:subslug/*" element={<div />} />
</Routes>
</>
)
export const App = () => (
<Routes>
<Route path="/" >
<Route path="post/*" element={<StreamPage />} />
<Route index element={<StreamPage />} />
</Route>
</Routes>
)
I know, I could fix the code by merging the two Routes blocks in StreamPage but I'm asking if this is expected behavior and if so what part of the react-router usage contract/API I'm violating? For instance, am I not allowed to have don't have sibling index routes under an index route? If I don't understand when/why this warning is produced I won't be able to avoid it in the future.
(related to this earlier question)
Related
I just can't find a way to set a default route with react-router v6
Is it because it's not good programming anymore?
Can somebody tell me why?
Thanks in advance
Rafael
If I understand your question about a "default" route correctly then I am interpreting this as one of the following:
Use an index route:
You can wrap a set of routes in a layout route and specify an index route:
<Routes>
<Route path="/*">
<Route index element={<ComponentA />} />
<Route path="pathB" element={<ComponentB />} />
<Route path="pathC" element={<ComponentC />} />
</Route>
</Routes>
The index route is the route that will be matched and rendered when the path exactly matches the root parent route's path.
Redirect to a "default" route if no other routes match:
You can also render a redirect to the route you consider to be the "default" route.
<Routes>
<Route path="/pathA" element={<ComponentA />} />
<Route path="/pathB" element={<ComponentB />} />
<Route path="/pathC" element={<ComponentC />} />
<Route path="*" element={<Navigate to="/pathA" replace />} />
</Routes>
TLDR;
use <Route index element={<Navigate to="/dashboard" />} />
index: default computed route.
<Navigate to="whatever you want"/>: is used to navigate to a another already declared path.
LR;
I found an easy way to redirect to a default component using index & Navigate combined.
In my situation I had used React Router V6.6.2 with:
createBrowserRouter(
createRoutesFromElements(...))
The routes look like this
/* All imports go here */
const router = createBrowserRouter(
createRoutesFromElements(
<Route element={<AuthLayout />}>
<Route element={<RrotectedLayout />}>
<Route path="/" element={<MainLayout />}>
<Route index element={<Navigate to="/dashboard" />} />
<Route path="dashboard" element={<Dashboard />} />
<Route path="projects" element={<Projects />} />
<Route path="users" element={<Users />} />
<Route path="notifications" element={<Notification />} />
<Route path="settings" element={<Settings />} />
<Route
path="*"
element={<Navigate to="/dashboard" replace={true} />}
/>
</Route>
</Route>
<Route path="/signup" element={<Signup />} />
<Route path="/login" element={<Login />} />
</Route>,
),
{},
)
export default function App() {
return (
<>
<RouterProvider router={router} />
</>
)
}
Now when you access your application, React router will figure out which index your application needs to point to, and since your index contains a Navigation to a specific path, you'll be redirect to that path by default. you don't need to specify a specific component (element) in this situation because you don't wanna loose the link to it.
I actually found the answer here but I just wanna share my solution if it helps someone with theirs.
You can set path='*' to make a default route. The index route deals a parent route ("/") but doesn't deal with routes which should otherwise return a 404 status.
if (!token) {
// This router will handle my public routes. Anything else is going to redirect to AuthPage without losing the previous route typed.
return (
<BrowserRouter>
<Routes>
{/* Auth */}
<Route path="/">
<Route exact path="recover" element={<UnknownPage />} />
// Default route
<Route path="*" element={<AuthPage setToken={setToken} />} />
</Route>
</Routes>
</BrowserRouter>
);
}
// This router is inside my application. Only logged users will get here.
return (
<BrowserRouter>
<Routes>
{/* My base page is just some fixed structure like Header, Sidebar and Footer. For this problem you can ignore it. */}
{/* BasePage */}
<Route path="/*" element={<BasePage logout={logout} />}>
{/* This is my specific users route */ }
{/* Users */}
<Route path="users">
<Route path="" element={<UsersPage />} />
<Route path=":id" element={<UserInfoPage />} />
</Route>
{/* Anything else is going to show this page. Even random words like: http:localhost:3000/anything-asdvasd */}
{/* Default Route */}
<Route path="*" element={<UnknownPage />} />
</Route>
</Routes>
</BrowserRouter>
);
Using parent routes like I used in my users routes makes it easier to scope your default routes.
If you are using createBrowserRouter you can set the default route in following way.
As per docs component loads children of parent. So
const router = createBrowserRouter([
{
path: "/",
element: <App />,
children: [
{
path: "/",
element: <Home />,
},
{
path: "/home",
element: <Home />,
},
],
},
],);
If you are using createBrowserRouter you can set the default route in following way.
const router = createBrowserRouter([
{
path: "/",
element: <RootLayout />,
children: [
{ index: true, element: <Navigate to="/calculation" replace /> },
{ path: "calculation", element: <Calculation /> },
{ path: "calendar", element: <Calendar /> },
{ path: "profile", element: <Profile /> },
],
},
]);
My application has scenarios where we need several routes to "pass" through a component to only then render the specifics, not only that but also situations where something is shown for the "parent" route and then split for the children...
It is imperative to note that we don't have a single "route config" file, and instead our routes are where we need them.
This was possible with v5, but I am very confused about how to get this accomplished with the new version.
So, currently we have stuff such as:
App.js
function App = () => {
return (
<Switch>
<Route exact path={['/', '/2', '/more-info']} component={Login} />
<Route path="/(main|settings|notifications)" component={AuthenticatedUser} />
<Redirect from="*" to="/404" />
</Switch>
);
}
AuthenticatedUser.js
function AuthenticatedUser= () => {
{... lots of common code}
return (
<div>
{...common html}
<Switch>
<Route exact path="/main" component={Main} />
<Route path="/settings" component={Settings} />
<Route path="/notifications" component={Notifications} />
</Switch>
</div>
);
}
Settings.js
function Settings= () => {
{... lots of common code}
return (
<div>
{...common html}
<Switch>
<Route exact path="/settings/basic" component={Basic} />
<Route exact path="/settings/notifications" component={Notifications} />
</Switch>
</div>
);
}
Now, with the relative from the parent, I am not able to get the same structure, I am also confused about how to get the routes split into separate files not even talking about the regex situation that I am guessing the solution is to duplicate the lines as many times as I have items in that regex...
You have basically 2 options when it comes to declaring the routes and sharing common UI:
Use layout routes and nested Route components.
Render routed components that render descendent routes in another Routes component wrapping descendent Route components.
Using layout and nested routes
Convert AuthenticatedUser into a layout route. Layout routes render an Outlet for nested routes to render their matched element into.
import { Outlet } from 'react-router-dom';
function AuthenticatedUser = () => {
{... lots of common code}
return (
<div>
{...common html}
<Outlet />
</div>
);
};
Convert Settings also into a layout route component.
import { Outlet } from 'react-router-dom';
function Settings = () => {
{... lots of common code}
return (
<div>
{...common html}
<Outlet />
</div>
);
};
App
import { Routes, Route, Navigate } from 'react-router-dom';
function App = () => {
return (
<Routes>
<Route path="/" element={<Login />} />
<Route path="/2" element={<Login />} />
<Route path="/more-info" element={<Login />} />
<Route element={<AuthenticatedUser />}>
<Route path="/main" element={<Main />} />
<Route path="/settings" element={<Settings />}>
<Route
path="basic" // "/settings/basic"
element={<Basic />}
/>
<Route
path="notifications" // "/settings/notifications"
element={<Notifications />}
/>
</Route>
<Route path="/notifications" element={<Notifications />} />
</Route>
<Route path="*" element={<Navigate to="/404" replace />} />
</Routes>
);
};
Using descendent routes
Here the parent routes need to render their route path with a trailing "*" wildcard matcher so descendent routes can also be matched. Descendent Routes components build their route paths relative to their parent Route path. I'd still suggest using AuthenticatedUser as a layout route for ease, otherwise you'll have a lot of code duplication since you'd need to wrap each route individually.
App
import { Routes, Route, Navigate } from 'react-router-dom';
function App = () => {
return (
<Routes>
<Route path="/" element={<Login />} />
<Route path="/2" element={<Login />} />
<Route path="/more-info" element={<Login />} />
<Route element={<AuthenticatedUser />}>
<Route path="/main" element={<Main />} />
<Route path="/settings/*" element={<Settings />} />
<Route path="/notifications" element={<Notifications />} />
</Route>
<Route path="*" element={<Navigate to="/404" replace />} />
</Routes>
);
};
Settings
import { Routes } from 'react-router-dom';
function Settings = () => {
{... lots of common code}
return (
<div>
{...common html}
<Routes>
<Route
path="/basic" // "/settings/basic"
element={<Basic />}
/>
<Route
path="/notifications" // "/settings/notifications"
element={<Notifications />}
/>
</Routes>
</div>
);
};
I'm attempting to create a few routes on my web app using react-router. However, some pages need to share components - such as the Navigation or Footer - where others do not.
What I essentially need is a way to check if a path doesn't match a few preset locations, and if it doesn't then render the content.
At the moment I'm doing this like so:
const displayComponentIfAllowed = (location, component) => {
const C = component;
const globalComponentsDisallowedPaths = ["/booking"];
// If the path matches something within the blocked list, then return null.
let allowToRender = true;
globalComponentsDisallowedPaths.forEach(disallowedPath => {
if(location.pathname === disallowedPath){
allowToRender = false;
}
});
// Otherwise, return component to render.
return allowToRender ? <C /> : null;
}
return (
<Router>
<Routes>
<Route render={({ location }) => displayComponentIfAllowed(location, Navigation)} />
<Route path="/">
<Route index element={<Home />} />
<Route path="booking/:customer_id" element={<Booking />} />
</Route>
<Route render={({ location }) => displayComponentIfAllowed(location, Footer)} />
</Routes>
</Router>
);
However, ever since V6 of react-router-dom has been introduced, this doesn't seem to work. I imagine this is because the render prop has been deprecated (although I'm unsure, but there's no mention of it in the docs).
Are there any workarounds - or a better implementation of this which works with V6? Cheers
Create a layout component that renders the UI components you want and an Outlet for nested routes to be rendered into.
Example:
import { Outlet } from 'react-router-dom';
const HeaderFooterLayout = () => (
<>
<Navigation />
<Outlet />
<Footer />
</>
);
...
import {
BrowserRouter as Router,
Routes,
Route
} from "react-router-dom";
...
<Router>
<Routes>
<Route element={<HeaderFooterLayout />} >
<Route path="/">
<Route index element={<Home />} />
... other routes you want to render with header/footer ...
</Route>
</Route>
<Route path="booking/:customer_id" element={<Booking />} />
... other routes you want to not render with header/footer ...
</Routes>
</Router>
I created this react component which has some nested routes. The problem is that the nested page component is either not rendering at all despite the URL changes or just returns a blank page.
I tried the suggestions from other posts like adding/removing exact in the parent route, but it's still not working.
Below are my codes:
// the parent component
<div className="App">
<Router>
<Navbar />
<Switch>
<Route exact path="/" render={() => <MyPage accessToken={accessToken} />}/>
<Route path="/editing/:playlistId" render={(props) =>
<EditingPlaylist {...props} accessToken={accessToken} />} />
</Switch>
</Router>
</div>
//the child component EditingPlaylist
render() {
const { pathname } = this.props.location;
return (
<div className="editing">
<Switch>
<Route exact path={pathname} render={() =>
<Searchbar accessToken={this.props.accessToken} />} />
<Route path={`${pathname}/test`} component={<p>Test</p>} />
<Route path={`${pathname}/album/:albumId`} render={
(props) => <AlbumPage {...props} accessToken={this.state.accessToken} />} />
<Route path={`${pathname}/artist/:artistId`} render={
(props) => <ArtistProfile {...props} accessToken={this.state.accessToken} />} />
</Switch>
</div>)
}
export default withRouter(EditingPlaylist);
Use url and path:
const { url, path } = this.props.match
to defined nested routes.
So, in nested routes:
<Switch>
<Route
exact
path={path} // HERE
render={() => <Searchbar accessToken={this.props.accessToken} />}
/>
...
</Switch>
There is a difference between url and path:
url: It is what is visible in the browser. e.g. /editing/123. This should be used in when redirecting via Link or history.push
path: It is what matched by the Route. e.g. /editing/:playlistId. This should be used when defining (nested) paths using Route.
From docs:
path - (string) The path pattern used to match. Useful for building nested <Route>s
url - (string) The matched portion of the URL. Useful for building nested <Link>s
I am trying to group some of my routes together with React Router v4 to clean up some of my components. For now I just want to have my non logged in routes group together and my admin routes grouped together but the following doens't work.
main.js
const Main = () => {
return (
<main>
<Switch>
<Route exact path='/' component={Public} />
<Route path='/admin' component={Admin} />
</Switch>
</main>
);
};
export default Main;
public.js
const Public = () => {
return (
<Switch>
<Route exact path='/' component={Greeting} />
<Route path='/signup' component={SignupPage} />
<Route path='/login' component={LoginPage} />
</Switch>
);
};
export default Public;
The Greeting component shows at "localhost:3000/", but the SignupPage component does not show at "localhost:3000/signup" and the Login component doesn't show at "localhost:3000/signup". Looking at the React Dev Tools these two routes return Null.
The reason is very obvious. for your route in main.js, you have specified the Route path of Public component with exact exact path='/' and then in the Public component you are matching for the other Routes. So if the route path is /signup, at first the path is not exact so Public component is not rendered and hence no subRoutes will.
Change your route configuration to the following
main.js
const Main = () => {
return (
<main>
<Switch>
<Route path='/' component={Public} />
<Route path='/admin' component={Admin} />
</Switch>
</main>
);
};
export default Main
public.js
const Public = () => {
return (
<Switch>
<Route exact path='/' component={Greeting} />
<Route path='/signup' component={SignupPage} />
<Route path='/login' component={LoginPage} />
</Switch>
);
};
Also when you are specifying the nested routes these should be relative to the parent Route, for instance if the parent route is /home and then in the child Route you wish to write /dashboard . It should be written like
<Route path="/home/dashboard" component={Dashboard}
or even better
<Route path={`${this.props.match.path}/dashboard`} component={Dashboard}