Search code examples
javascriptreactjsreact-routerreact-router-v4

Is it possible to have multiple <Switch> in React.js?


I am building a React project without Redux.

I would love to have two, or in this case 3 different Switches

1st Switch will be able to Switch between Home page (normal website) and UserPage (Dashboard) when user is logged in... Then each of this will be Switchers as well, so Home will Switch among Home components, and UserPage will switch among UserPage components. Is this even possible?

                        Main Switcher 
     Home Page (Switch)              Dashboard
Home About Contact, Careers     My Profile, Courses, Classes, Donations...

This is how project should look like and should be structured.


Solution

  • You can use as many Switch components as you want. It simply renders the first match of all the routes specified under it.

    Something along these lines should work, in your case:

    const Home = ({match}) => {
      return(
        <Switch>
          <Route path={match.url} exact={true} component={HomeDefaultComponent} />
          <Route path={`${match.url}/about`} exact={true} component={About} />
          <Route path={`${match.url}/contact`} exact={true} component={Contact} />
          <Route path={`${match.url}/careers`} exact={true} component={careers} />
        </Switch>
      );
    };
    
    const Dashboard = ({match}) => {
      return(
        <Switch>
          <Route path={match.url} exact={true} component={DashboardDefaultComponent} />
          ... other Dashboard paths like Home component above
        </Switch>
      );
    };
    
    const App = () => {
      return(
        <Switch>
          <Route path='/home' component={Home} />
          <Route path='/dashboard' component={Dashboard} />
        </Switch>
      );
    }