React Switch Route Default

Asked

Viewed 201 times

3

I’m creating an app in Nodejs, React & Redux here at the company. And I have a page that is Content, in it I have two navigation bars and a common area for content. In this common area I’m using Switch to control the routes, but I want a route (component) to enter as soon as the app is loaded, IE, be the default, but I’m not finding documentation about it, can help me, below follows the code.

import React, { Fragment } from 'react';
import { BrowserRouter as Router, Route, Switch } from 'react-router-dom';

import Navbar from './Navbar';
import Topnavbar from './Topnavbar';
import Dashboard from './Dashboard';
import Profile from './Profile';

const Content = () => {
  return (
    <Router>
      <Fragment>
        <div id='wrapper'>
          <Navbar />
          <div id='content-wrapper' className='d-flex flex-column'>
            <div id='content'>
              <Topnavbar />
              <Switch>
                <Route exact path='/dashboard' component={Dashboard} />
                <Route exact path='/profile' component={Profile} />
              </Switch>
            </div>
          </div>
        </div>
      </Fragment>
    </Router>
  );
};

export default Content;

I want the Dashboard component to be the default. How to determine that a route is the default on the switch?

Thank you.

2 answers

2

You can use the component Redirect.

Gets something like this:

<Switch>
 <Route exact path='/dashboard' component={Dashboard} default />
 <Route exact path='/profile' component={Profile} />
 <Redirect exact from="/" to="/dashboard"/> 
</Switch>

This means that when the application loads (normally this starts with "/") then you will redirect to "/Dashboard".

There is also another way, which worked in the v4 of the react-router, but I’m not sure in v5.

<Switch>
  <Route exact path='/dashboard' component={Dashboard} default />
  <Route exact path='/profile' component={Profile} />
  <Route render={() => <Redirect to="/dashboard"/>}/>
</Switch>

Put a component Route without path will cause it to be executed always. However, as in this case it finds itself in the last order within a switch, it will only be executed if I don’t pass by any other Route previous.

In other words, if the path go to some other than "/Dashboard" or "/profile" it will redirect to "/Dashboard" always.

  • Thanks Andrew, I used Redirect but instead of a "/" I used "/content" to "/Dashboard" because my application uses the "/" to always go to login, since it runs on an intranet and has the need to always login to access it.

  • I’m glad it worked out.

0

Try to do this:

<Switch>
    <Route path="/sua rota" exact component={seu componente aqui} />
</Switch>

Browser other questions tagged

You are not signed in. Login or sign up in order to post.