[javascript] How to set the DefaultRoute to another Route in React Router

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

This question is related to javascript routes reactjs url-redirection react-router

The answer is


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>

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"/>
  )
)}/>

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


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


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.


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>

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>

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

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>

UPDATE : 2020

Instead of using Redirect, Simply add multiple route in the path

Example:

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

Examples related to javascript

need to add a class to an element How to make a variable accessible outside a function? Hide Signs that Meteor.js was Used How to create a showdown.js markdown extension Please help me convert this script to a simple image slider Highlight Anchor Links when user manually scrolls? Summing radio input values How to execute an action before close metro app WinJS javascript, for loop defines a dynamic variable name Getting all files in directory with ajax

Examples related to routes

How to open a link in new tab using angular? How to Refresh a Component in Angular laravel Unable to prepare route ... for serialization. Uses Closure How to use router.navigateByUrl and router.navigate in Angular No provider for Router? Difference between [routerLink] and routerLink How to force Laravel Project to use HTTPS for all routes? Change route params without reloading in Angular 2 Angular 2 router no base href set How to redirect to a route in laravel 5 by using href tag if I'm not using blade or any template?

Examples related to reactjs

Error: Node Sass version 5.0.0 is incompatible with ^4.0.0 TypeError [ERR_INVALID_ARG_TYPE]: The "path" argument must be of type string. Received type undefined raised when starting react app Template not provided using create-react-app How to resolve the error on 'react-native start' Element implicitly has an 'any' type because expression of type 'string' can't be used to index Invalid hook call. Hooks can only be called inside of the body of a function component How to style components using makeStyles and still have lifecycle methods in Material UI? React Hook "useState" is called in function "app" which is neither a React function component or a custom React Hook function How to fix missing dependency warning when using useEffect React Hook? Unable to load script.Make sure you are either running a Metro server or that your bundle 'index.android.bundle' is packaged correctly for release

Examples related to url-redirection

How to set the DefaultRoute to another Route in React Router MVC Redirect to View from jQuery with parameters Go to URL after OK button if alert is pressed How do you redirect to a page using the POST verb?

Examples related to react-router

React : difference between <Route exact path="/" /> and <Route path="/" /> You should not use <Link> outside a <Router> React Router Pass Param to Component Detect Route Change with react-router What is the best way to redirect a page using React Router? No restricted globals React-router v4 this.props.history.push(...) not working How to pass params with history.push/Link/Redirect in react-router v4? How to use Redirect in the new react-router-dom of Reactjs How to implement authenticated routes in React Router 4?