139

I have the following:

  <Route name="app" path="/" handler={App}>
    <Route name="dashboards" path="dashboards" handler={Dashboard}>
      <Route name="exploreDashboard" path="exploreDashboard" handler={ExploreDashboard} />
      <Route name="searchDashboard" path="searchDashboard" handler={SearchDashboard} />
      <DefaultRoute handler={DashboardExplain} />
    </Route>
    <DefaultRoute handler={SearchDashboard} />
  </Route>

When using the DefaultRoute, SearchDashboard renders incorrectly since any *Dashboard needs to rendered within Dashboard.

I would like for my DefaultRoute within the "app" Route to point to the Route "searchDashboard". Is this something that I can do with React Router, or should I use normal Javascript (for a page redirect) for this?

Basically, if the user goes to the home page I want to send them instead to the search dashboard. So I guess I'm looking for a React Router feature equivalent to window.location.replace("mygreathostname.com/#/dashboards/searchDashboard");

Matthew Herbst
  • 29,477
  • 23
  • 85
  • 128

19 Answers19

188

You can use Redirect instead of DefaultRoute

<Redirect from="/" to="searchDashboard" />

Update 2019-08-09 to avoid problem with refresh use this instead, thanks to Ogglas

<Redirect exact from="/" to="searchDashboard" />

Source:

https://stackoverflow.com/a/43958016/3850405

Ogglas
  • 62,132
  • 37
  • 328
  • 418
Jonatan Lundqvist Medén
  • 2,750
  • 1
  • 17
  • 15
  • 6
    is it just me, or when using this to hit a deep url directly, I always get redirected to the "to" url, instead of the route I'm trying to hit? – Pablote Apr 17 '17 at 18:47
  • Should be noticed that if you are doing some redirection like `from='/a' to='/a/:id'`, you will need to use `` to include your `` and `` component from react-router. Details see [doc](https://github.com/ReactTraining/react-router/blob/dc2149ec0c63bfc95b71e40c81431e34cfbfeda9/packages/react-router/docs/api/Redirect.md#from-string) – Kulbear May 24 '17 at 09:08
  • 1
    @Kulbear I had the same problem. Doing what Ogglas said in his answer worked. – Alan P. Jun 22 '17 at 23:46
  • 2
    To make it work you most likely need to put this route last or do this `` – Aleksei Poliakov Apr 27 '19 at 19:27
  • It's easy to oversee it, so I repeat: The important part of DarkWalker's Redirect rule is the `exact` flag. The acceptet answer is missing that, so it matches [almost] any route. – dube May 15 '19 at 11:32
  • Redirect has been removed from React Router Dom – Uzair_07 Jan 09 '22 at 10:31
93

Update for version 6.4.5 to 6.8.1 <:

Use replace={true} for Navigate component.

<Routes>
  <Route path="/" element={<Navigate to="/searchDashboard" replace={true} />}>
    <Route path="searchDashboard" element={<SearchDashboard/>} />
    <Route
      path="*"
      element={<Navigate to="/" replace={true} />}
    />
  </Route>
</Routes>

https://reactrouter.com/en/6.4.5/components/navigate https://reactrouter.com/en/6.8.1/components/navigate

Thanks to @vicky for pointing this out in comments.

Update:

For v6 you can do it like this with Navigate. You can use a "No Match" Route to handle "no match" cases.

<Routes>
  <Route path="/" element={<Navigate to="/searchDashboard" />}>
    <Route path="searchDashboard" element={<SearchDashboard/>} />
    <Route
      path="*"
      element={<Navigate to="/" />}
    />
  </Route>
</Routes>

https://reactrouter.com/docs/en/v6/getting-started/tutorial#adding-a-no-match-route

https://stackoverflow.com/a/69872699/3850405

Original:

The problem with using <Redirect from="/" to="searchDashboard" /> is if you have a different URL, say /indexDashboard and the user hits refresh or gets a URL sent to them, the user will be redirected to /searchDashboard anyway.

If you wan't users to be able to refresh the site or send URLs use this:

<Route exact path="/" render={() => (
    <Redirect to="/searchDashboard"/>
)}/>

Use this if searchDashboard is behind login:

<Route exact path="/" render={() => (
  loggedIn ? (
    <Redirect to="/searchDashboard"/>
  ) : (
    <Redirect to="/login"/>
  )
)}/>
Ogglas
  • 62,132
  • 37
  • 328
  • 418
38

I was incorrectly trying to create a default path with:

<IndexRoute component={DefaultComponent} />
<Route path="/default-path" component={DefaultComponent} />

But this creates two different paths that render the same component. Not only is this pointless, but it can cause glitches in your UI, i.e., when you are styling <Link/> elements based on this.history.isActive().

The right way to create a default route (that is not the index route) is to use <IndexRedirect/>:

<IndexRedirect to="/default-path" />
<Route path="/default-path" component={DefaultComponent} />

This is based on react-router 1.0.0. See https://github.com/rackt/react-router/blob/master/modules/IndexRedirect.js.

Seth
  • 6,514
  • 5
  • 49
  • 58
  • What's the point of having a `Route` to something that is already handled by your `IndexRoute`? – Matthew Herbst Dec 04 '15 at 03:52
  • 1
    There is no point, and I edited my answer to make it clear I was not advocating that. – Seth Dec 04 '15 at 03:58
  • This is what I've been doing as well, but I'd love a solution that serves up a component (my homepage) at `/` instead of having to redirect to e.g. `/home`. – ericsoco Aug 08 '16 at 23:39
  • Looks like I'm looking for `` after all. Sorry for the noise. http://stackoverflow.com/questions/32706913/react-router-what-is-the-purpose-of-indexroute https://github.com/reactjs/react-router/blob/master/docs/guides/IndexRoutes.md#index-routes – ericsoco Aug 08 '16 at 23:42
13

2020:

Instead of using Redirect, simply add multiple routes in the path.

Example:

<Route exact path={["/","/defaultPath"]} component={searchDashboard} />

UPDATE 2023

This doesn't work in v6, so use this instead

<Route exact path="/" element={searchDashboard} />
<Route exact path="/defaultPath" element={searchDashboard} />
Thanveer Shah
  • 3,250
  • 2
  • 15
  • 31
  • 1
    Hey are you sure there are square brackets there? Because I was getting the error: ```"Uncaught TypeError: meta.relativePath.startsWith is not a function" ``` so when I removed the square brackets, it works fine, like this: `````` – Uzair_07 Jan 09 '22 at 10:30
12

Jonathan's answer didn't seem to work for me. I'm using React v0.14.0 and React Router v1.0.0-rc3. This did:

<IndexRoute component={Home}/>.

So in Matthew's Case, I believe he'd want:

<IndexRoute component={SearchDashboard}/>.

Source: https://github.com/rackt/react-router/blob/master/docs/guides/advanced/ComponentLifecycle.md

dwilt
  • 617
  • 9
  • 13
  • Thanks for the share. I was using React v0.13 and the version of React-Router for that, so a pre-1.0/rc version. Hope this helps others! – Matthew Herbst Oct 14 '15 at 14:59
  • I think this makes you lose the context. `SearchDashboard` will be the component you will see when you arrive at the homepage, but not the `Dashboard` component that is wrapping it if you go directly to `/dashboard/searchDashboard`. React-router dynamically builds up a hierarchy of nested components based on the routes matched by the URL, so I think you really do need a redirect here. – Stijn de Witt Jan 19 '16 at 12:34
12

Since V6 was released recently, the accepted answer won't work since Redirect no more exists in V6. Consider using Navigate.

 <Route path="/" element={<Navigate to="/searchDashboard" />} />

Ref:- V6 docs

Bijan Kundu
  • 415
  • 5
  • 11
7
import { Route, Redirect } from "react-router-dom";

class App extends Component {
  render() {
    return (
      <div>
        <Route path='/'>
          <Redirect to="/something" />
        </Route>
//rest of code here

this will make it so that when you load up the server on local host it will re direct you to /something

7

May 2022

  1. Import Navigate
import { Routes, Route, Navigate } from 'react-router-dom';
  1. Add
<Route path="/" element={<Navigate replace to="/home" />} />

For example:

import React from 'react';
import { Routes, Route, Navigate } from 'react-router-dom';

import Home from './pages/Home';
import Login from './pages/Login';

const Main = () => {
    return (
        <Routes>
            <Route path="/" element={<Navigate replace to="/home" />} />
            <Route path='home' element={<Home />}></Route>
            <Route path='login' element={<Login />}></Route>
        </Routes>
    );
}

export default Main;
  1. Done!
hadeneh
  • 111
  • 1
  • 7
4

I ran into a similar issue; I wanted a default route handler if none of the route handler matched.

My solutions is to use a wildcard as the path value. ie Also make sure it is the last entry in your routes definition.

<Route path="/" component={App} >
    <IndexRoute component={HomePage} />
    <Route path="about" component={AboutPage} />
    <Route path="home" component={HomePage} />
    <Route path="*" component={HomePage} />
</Route>
devil_io
  • 191
  • 2
  • 5
4

For those coming into 2017, this is the new solution with IndexRedirect:

<Route path="/" component={App}>
  <IndexRedirect to="/welcome" />
  <Route path="welcome" component={Welcome} />
  <Route path="about" component={About} />
</Route>
Kevin Hernandez
  • 522
  • 1
  • 6
  • 20
2
 <Route name="app" path="/" handler={App}>
    <Route name="dashboards" path="dashboards" handler={Dashboard}>
      <Route name="exploreDashboard" path="exploreDashboard" handler={ExploreDashboard} />
      <Route name="searchDashboard" path="searchDashboard" handler={SearchDashboard} />
      <DefaultRoute handler={DashboardExplain} />
    </Route>
    <Redirect from="/*" to="/" />
  </Route>
1

The preferred method is to use the react router IndexRoutes component

You use it like this (taken from the react router docs linked above):

<Route path="/" component={App}>
    <IndexRedirect to="/welcome" />
    <Route path="welcome" component={Welcome} />
    <Route path="about" component={About} />
</Route>
Marc Costello
  • 439
  • 1
  • 3
  • 12
1

Firstly you need to install:

npm install react-router-dom;

Then you need to use your App.js (in your case it can be different) and do the modification below. In this case I selected the Redirect to get proper rendering process.

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

<Router>
        <Suspense fallback={<Loading />}>
          <Switch>
            <Route exact path="/">
              <Redirect to="/Home" component={Routes.HomePage}/>
            </Route>
            <Route exact path="/Biz" component={Routes.Biz} />
          </Switch>
        </Suspense>
      </Router>

If you successfully do the modification above, you can see the redirect URL is on your browser path and rendering process also working properly according to their component.

Some time ago, we had an opportunity to use the component named "DefaultRoute" in the react routing.

Now, it's a deprecated method, and it’s not so popular to use it. You can create the custom route named default or whatever, but still, it’s not how we do it in modern React.js development.

It’s just because using the "DefaultRoute" route, we can cause some rendering problems, and it's the thing that we definitely would like to avoid.

Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
1

Here is how I do it-

<Router>
  <div className="App">
    <Navbar />
    <TabBar />
    <div className="content">
      <Route exact path={["/default", "/"]}> //Imp
        <DefStuff />
      </Route>
      <Route exact path="/otherpage">
        <Otherstuff />
      </Route>
      <Redirect to="/defult" /> //Imp
    </div>
  </div>
</Router>
prakhar tomar
  • 933
  • 1
  • 8
  • 10
1

Use:

<Route path="/" element={<Navigate replace to="/expenses" />} />

In context:

import { BrowserRouter, Routes, Route, Navigate } from "react-router-dom";

<BrowserRouter>
  <Routes>
    <Route element={<App />}>
      <Route path="/expenses" element={<Expenses />} />
      <Route path="/invoices" element={<Invoices />} />
    </Route>
    <Route path="/" element={<Navigate replace to="/expenses" />} />
  </Routes>
</BrowserRouter>
Bar Horing
  • 5,337
  • 3
  • 30
  • 26
0

You use it like this to redirect on a particular URL and render component after redirecting from old-router to new-router.

<Route path="/old-router">
  <Redirect exact to="/new-router"/>
  <Route path="/new-router" component={NewRouterType}/>
</Route>
surbhi241
  • 81
  • 1
  • 2
0

Place the following code after all the exact routes. If none of them matches the current route, it'll render the default route.

<Route path="*" element={<DefaultComponent />} />
Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
0

Redirect to /Home when user goes to / (default Route):

 <Route path="/" element={<Navigate to="/Home" />} />

Use the Navigate element to redirect the user to /Home every time they go to the / route.

Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
Avnish Jayaswal
  • 161
  • 1
  • 4
-3

You can achieve the desired behavior by using the Switch component and placing the default route at the end:

  1. Import the necessary components from React Router in your application:
    import { BrowserRouter as Router, Switch, Route } from 'react-router-dom';
    
  2. Define your routes in the `Switch` component, placing the default route at the end:
    <Router>
      <Switch>
        <Route exact path="/" component={Home} />
        <Route path="/users" component={Users} />
        <Route path="/profile/:id" component={Profile} />
        <Route component={DefaultRoute} />
      </Switch>
    </Router>
    
In this example:
- The first route matches the exact path `/` and renders the `Home` component.
- The second route matches the path `/users` and renders the `Users` component.
- The third route matches the path `/profile/:id` and renders the `Profile` component. This route requires an `id` parameter.
- The last route, without a specified path, acts as the default route and renders the `DefaultRoute` component. This component will be shown when none of the previous routes match the current URL.
To handle 404 errors this way, define the `DefaultRoute` component and import it into your application.
function DefaultRoute() {
  return (
    <div>
      <h2>404 Not Found</h2>
      <p>The page you are looking for does not exist.</p>
    </div>
  );
}

export default DefaultRoute;

With this setup, if none of the routes match the current URL, the DefaultRoute component will be rendered, serving as the default route. You can customize the DefaultRoute component to display a custom 404 page or any other desired content.

Source: https://www.devban.com/react-router-ultimate-guide/

  • 1
    This answer looks like it was mostly written by ChatGPT, and may be mainly an excuse to link to your site – DavidW Jul 13 '23 at 09:51
  • 2
    An answer that looks AI-assisted pointing to a blog that looks AI-assisted? Say it ain't so! Welcome to Stack overflow, Mostafa Safarian, both of your existing answers here appear likely to be entirely or partially written by AI (e.g., ChatGPT). Please be aware that [posting AI-generated content is not allowed here](//meta.stackoverflow.com/q/421831). If you used an AI tool to assist with any answer, I would encourage you to delete it. We do hope you'll stick around and be a valuable part of our community by posting *your own* quality content. Thanks! – NotTheDr01ds Jul 13 '23 at 23:03
  • 2
    Also note that Stack Exchange policy requires you to mention any affiliation with a site you link to. The fact that your username is the same as the name of the blog isn't sufficient, since usernames can change. – NotTheDr01ds Jul 13 '23 at 23:04
  • 2
    **Readers should review this answer carefully and critically, as AI-generated information often contains fundamental errors and misinformation.** If you observe quality issues and/or have reason to believe that this answer was generated by AI, please leave feedback accordingly. – NotTheDr01ds Jul 13 '23 at 23:04
  • This answer has a high probability of being AI generated. This is **not tolerated** on this site. Read the guidelines of AI content here: https://stackoverflow.com/help/gpt-policy –  Jul 15 '23 at 13:04