react-router#Switch JavaScript Examples

The following examples show how to use react-router#Switch. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example #1
Source File: index.js    From choerodon-front-base with Apache License 2.0 6 votes vote down vote up
Index = ({ match }) => (
  <Switch>
    <PermissionRoute
      exact
      path={match.url}
      component={RoleIndex}
      service={['choerodon.code.organization.manager.role.ps.default']}
    />
    <Route path="*" component={NoMatch} />
  </Switch>
)
Example #2
Source File: renderRoutes.js    From the-eye-knows-the-garbage with MIT License 6 votes vote down vote up
function renderRoutes(routes, extraProps = {}, switchProps = {}) {
  return routes ? (
    <Switch {...switchProps}>
      {routes.map((route, i) => (
        <Route
          key={route.key || i}
          path={route.path}
          exact={route.exact}
          strict={route.strict}
          render={props =>
            route.render ? (
              route.render({ ...props, ...extraProps, route: route })
            ) : (
              <route.component {...props} {...extraProps} route={route} />
            )
          }
        />
      ))}
    </Switch>
  ) : null;
}
Example #3
Source File: react-router-config.js    From the-eye-knows-the-garbage with MIT License 6 votes vote down vote up
function renderRoutes(routes, extraProps, switchProps) {
  if (extraProps === void 0) {
    extraProps = {};
  }

  if (switchProps === void 0) {
    switchProps = {};
  }

  return routes ? React.createElement(Switch, switchProps, routes.map(function (route, i) {
    return React.createElement(Route, {
      key: route.key || i,
      path: route.path,
      exact: route.exact,
      strict: route.strict,
      render: function render(props) {
        return route.render ? route.render(_extends({}, props, {}, extraProps, {
          route: route
        })) : React.createElement(route.component, _extends({}, props, extraProps, {
          route: route
        }));
      }
    });
  })) : null;
}
Example #4
Source File: wallet-router.js    From albedo with MIT License 6 votes vote down vote up
export default function WalletRouter() {
    const {path} = useRouteMatch()
    return <AccountContextView>
        <Switch>
            <Route path={`${path}/swap`} component={SwapView}/>
            <Route path={`${path}/transfer`} component={TransferView}/>
            <Route path={`${path}/add-trustline`} component={AddTrustlineView}/>
            <Route path={`${path}/liquidity-pool`} component={LiquidityPoolsRouter}/>
            <Route component={NotFound}/>
        </Switch>
    </AccountContextView>
}
Example #5
Source File: liquidity-pools-router.js    From albedo with MIT License 6 votes vote down vote up
export default function LiquidityPoolsRouter() {
    const {path} = useRouteMatch()
    return <Switch>
        <Route path={`${path}/deposit`} component={DepositView}/>
        <Route path={`${path}/withdraw`} component={WithdrawView}/>
        <Route path={`${path}`} exact component={LiquidityPoolView}/>
        <Route component={NotFound}/>
    </Switch>
}
Example #6
Source File: app-router.js    From albedo with MIT License 6 votes vote down vote up
export default function AppRouter({history}) {
    return <Layout>
        <Router history={history}>
            <CatcherView>
                <Switch>
                    <Route path="/playground">
                        <DynamicModule load={() => import(/* webpackChunkName: "playground" */ './demo/demo-view')}
                                       moduleKey="playground"/></Route>
                    <Route path="/wallet">
                        <DynamicModule load={() => import(/* webpackChunkName: "wallet" */ './wallet/wallet-router')}
                                       moduleKey="wallet"/></Route>
                    <Route path="/login" component={Login}/>
                    <Route path="/import" component={ImportAccount}/>
                    <Route path="/signup" component={CreateAccount}/>
                    <Route path="/confirm" component={Intent}/>
                    <Route path="/result" component={TxResultView}/>
                    <Route path="/account" component={AccountDashboard}/>
                    <Route path="/extension" component={AccountDashboard}/>
                    <Route path="/account-settings" component={AccountSettings}/>
                    <Route path="/blocked" component={BlockedPageView}/>
                    <Route path="/install-extension" component={InstallExtensionView}/>
                    <Route path="/web-stellar-handler" component={WebStellarLinkHandler}/>
                    <Route path="/" exact component={IntroView}/>
                    <Route component={NotFound}/>
                </Switch>
            </CatcherView>
        </Router>
    </Layout>
}
Example #7
Source File: App.js    From Women-in-Technology with MIT License 6 votes vote down vote up
function App() {
  return (
    <div className="App">
      <Router>
        <Header />
        <Switch>
          <Route path="/" exact component={IndexPage} />
          <Route path="/scholarship" exact component={ScholarshipPage} />
          <Route path="/resources" exact component={ResourcesPage} />
          <Route path="/organisation" exact component={OrganisationComponent} />
          {/* <Route path="/infographics" exact component={infographics} /> */}
          <Route path="/articless" exact component={ArticlesPage} />
          <Route path="/community" exact component={CommunityPage} />
          <Route path="/inspirations" exact component={inspirations} />
          <Route path="/contributing" exact component={ContributingPage} />
          <Route path="/github" exact component={GithubPage} />
          <Route path="/events" exact component={EventsPage} />
        </Switch>
        <Footer />
      </Router>
      <ScrollButton />
    </div>
  );
}
Example #8
Source File: DiscussionSidebar.jsx    From frontend-app-discussions with GNU Affero General Public License v3.0 6 votes vote down vote up
export default function DiscussionSidebar({ displaySidebar }) {
  const location = useLocation();

  return (
    <div
      className={classNames('flex-column', {
        'd-none': !displaySidebar,
        'd-flex w-25 w-xs-100 w-lg-25 overflow-auto h-100': displaySidebar,
      })}
      style={{ minWidth: '30rem' }}
      data-testid="sidebar"
    >
      <Switch>
        <Route
          path={[Routes.POSTS.PATH, Routes.POSTS.ALL_POSTS, Routes.TOPICS.CATEGORY, Routes.POSTS.MY_POSTS]}
          component={PostsView}
        />
        <Route path={Routes.TOPICS.PATH} component={TopicsView} />
        <Route path={Routes.LEARNERS.POSTS} component={LearnerPostsView} />
        <Route path={Routes.LEARNERS.PATH} component={LearnersView} />
        <Redirect
          from={Routes.DISCUSSIONS.PATH}
          to={{
            ...location,
            pathname: Routes.POSTS.ALL_POSTS,
          }}
        />
      </Switch>
    </div>
  );
}
Example #9
Source File: DiscussionContent.jsx    From frontend-app-discussions with GNU Affero General Public License v3.0 6 votes vote down vote up
export default function DiscussionContent() {
  const refContainer = useRef(null);
  const postEditorVisible = useSelector((state) => state.threads.postEditorVisible);
  useContainerSizeForParent(refContainer);

  return (
    <div className="d-flex bg-light-400 flex-column w-75 w-xs-100 w-xl-75 align-items-center h-100 overflow-auto">
      <div className="d-flex flex-column w-100 mw-xl" ref={refContainer}>
        {postEditorVisible ? (
          <Route path={Routes.POSTS.NEW_POST}>
            <PostEditor />
          </Route>
        ) : (
          <Switch>
            <Route path={Routes.POSTS.EDIT_POST}>
              <PostEditor editExisting />
            </Route>
            <Route path={Routes.COMMENTS.PATH}>
              <CommentsView />
            </Route>
          </Switch>
        )}
      </div>
    </div>
  );
}
Example #10
Source File: DiscussionsSettings.test.jsx    From frontend-app-course-authoring with GNU Affero General Public License v3.0 6 votes vote down vote up
function renderComponent() {
  const wrapper = render(
    <AppProvider store={store}>
      <PagesAndResourcesProvider courseId={courseId}>
        <Switch>
          <PageRoute
            path={[
              `/course/${courseId}/pages-and-resources/discussion/configure/:appId`,
              `/course/${courseId}/pages-and-resources/discussion`,
            ]}
          >
            <DiscussionsSettings courseId={courseId} />
          </PageRoute>
        </Switch>
      </PagesAndResourcesProvider>
    </AppProvider>,
  );
  container = wrapper.container;
}
Example #11
Source File: CourseAuthoringRoutes.jsx    From frontend-app-course-authoring with GNU Affero General Public License v3.0 6 votes vote down vote up
/**
 * As of this writing, these routes are mounted at a path prefixed with the following:
 *
 * /course/:courseId
 *
 * Meaning that their absolute paths look like:
 *
 * /course/:courseId/course-pages
 * /course/:courseId/proctored-exam-settings
 * /course/:courseId/editor/:blockType/:blockId
 *
 * This component and CourseAuthoringPage should maybe be combined once we no longer need to have
 * CourseAuthoringPage split out for use in LegacyProctoringRoute.  Once that route is removed, we
 * can move the Header/Footer rendering to this component and likely pull the course detail loading
 * in as well, and it'd feel a bit better-factored and the roles would feel more clear.
 */
export default function CourseAuthoringRoutes({ courseId }) {
  const { path } = useRouteMatch();
  return (
    <CourseAuthoringPage courseId={courseId}>
      <Switch>
        <PageRoute path={`${path}/pages-and-resources`}>
          <PagesAndResources courseId={courseId} />
        </PageRoute>
        <PageRoute path={`${path}/proctored-exam-settings`}>
          <ProctoredExamSettings courseId={courseId} />
        </PageRoute>
        <PageRoute path={`${path}/editor/:blockType/:blockId`}>
          {process.env.ENABLE_NEW_EDITOR_PAGES === 'true'
            && (
            <EditorContainer
              courseId={courseId}
            />
            )}
        </PageRoute>
      </Switch>
    </CourseAuthoringPage>
  );
}
Example #12
Source File: index.js    From choerodon-front-base with Apache License 2.0 6 votes vote down vote up
Index = ({ match }) => (
  <Switch>
    <PermissionRoute
      exact
      path={match.url}
      component={TabIndex}
      service={['choerodon.code.site.setting.security.ps.password-policy']}
    />
    <Route path="*" component={NoMatch} />
  </Switch>
)
Example #13
Source File: index.js    From choerodon-front-base with Apache License 2.0 6 votes vote down vote up
Index = ({ match }) => (
  <Switch>
    <PermissionRoute
      path={match.url}
      component={TabIndex}
      service={['choerodon.code.organization.setting.security.ps.password-policy']}
    />
    <Route path="*" component={NoMatch} />
  </Switch>
)
Example #14
Source File: index.js    From choerodon-front-base with Apache License 2.0 6 votes vote down vote up
Index = ({ match }) => (
  <Switch>
    <PermissionRoute
      exact
      path={match.url}
      component={ContentIndex}
      service={['choerodon.code.site.manager.platform-overview.ps.default']}
    />
    <Route path="*" component={NoMatch} />
  </Switch>
)
Example #15
Source File: index.js    From choerodon-front-base with Apache License 2.0 6 votes vote down vote up
Index = ({ match }) => (
  <Switch>
    <PermissionRoute
      exact
      path={match.url}
      component={ContentIndex}
      service={['choerodon.code.organization.manager.overview.ps.default']}
    />
    <Route path="*" component={NoMatch} />
  </Switch>
)
Example #16
Source File: App.js    From light-blue-react-template with MIT License 6 votes vote down vote up
render() {
    return (
        <div>
            <ToastContainer
                autoClose={5000}
                hideProgressBar
                closeButton={<CloseButton/>}
            />
            <HashRouter>
                <Switch>
                    <Route path="/" exact render={() => <Redirect to="/app/main"/>}/>
                    <Route path="/app" exact render={() => <Redirect to="/app/main"/>}/>
                    <PrivateRoute path="/app" dispatch={this.props.dispatch} component={LayoutComponent}/>
                    <Route path="/register" exact component={Register}/>
                    <Route path="/login" exact component={Login}/>
                    <Route path="/error" exact component={ErrorPage}/>
                    <Route component={ErrorPage}/>
                    <Redirect from="*" to="/app/main/dashboard"/>
                </Switch>
            </HashRouter>
        </div>

    );
  }
Example #17
Source File: index.js    From TimesOfInternet with MIT License 6 votes vote down vote up
ReactDOM.render(
  <Router history={hist}>
    <Switch>
      <Route path="/" exact component={BlogPostPage} />
      <Route path="/about" component={AboutUsPage} />
      <Route path="/contact" component={ContactUsPage} />
      <Route component={ErrorPage} />
    </Switch>
  </Router>,
  document.getElementById("root")
);
Example #18
Source File: index.js    From Registration-Login-and-CRUD-Action-using-MERN-stack with GNU General Public License v3.0 6 votes vote down vote up
ReactDOM.render(
    <BrowserRouter>
        <Switch>
            <Route exact path='/' component={Login} />
            <Route exact path='/register' component={Register} />
            <Route path='/dashboard' component={Dashboard} />
            {/* <Route component={NotFound}/> */}
        </Switch>
    </BrowserRouter>,
    document.getElementById('root')
);
Example #19
Source File: routes.js    From college-management-react with GNU General Public License v3.0 6 votes vote down vote up
render() {
    return (
      <Switch>
        <Fragment>
          <Paper>
            <div className="main-cointainer">
              <Route exact path="/login" component={Login} />
              <PrivateRoute exact path="/" component={Home} />
              <PrivateRoute exact path="/profile" component={Profile} />
              <PrivateRoute exact path="/users/:id" component={UserEdit} roles={["ADMIN"]}/>
              <PrivateRoute exact path="/users" component={UserList} roles={["ADMIN"]}/>
              
              {/* CUSTOM VIEWS */}

              <PrivateRoute exact path="/home" component={Home} />

              {/* START MY VIEWS */}

              <PrivateRoute exact path="/courses/:id" component={ CourseEdit }  />
              <PrivateRoute exact path="/courses" component={ CourseList }  />
              <PrivateRoute exact path="/exams/:id" component={ ExamEdit }  />
              <PrivateRoute exact path="/exams" component={ ExamList }  />
              <PrivateRoute exact path="/students/:id" component={ StudentEdit }  />
              <PrivateRoute exact path="/students" component={ StudentList }  />
              <PrivateRoute exact path="/teachers/:id" component={ TeacherEdit }  />
              <PrivateRoute exact path="/teachers" component={ TeacherList }  />

             {/* END MY VIEWS */}

            </div>
          </Paper>
        </Fragment>
      </Switch>
    );
  }
Example #20
Source File: BookingPage.js    From git-brunching with GNU General Public License v3.0 6 votes vote down vote up
BookingPage = (props) => {
  const memoryHistory = createMemoryHistory();
  const history = useHistory();
  const { selected } = props;


  return (
    <div className={style.container}>
      {selected == null ? <NotFound />
        : (
          <div className={style.contentContainer}>
            {/* A surrounding div for styling purposes */}
            <div className={style.headerContainer}>
              <div className={style.header}>
                <div
                  className={style.logo}
                  onClick={() => { if (window.confirm('Are you sure you want to leave before booking? Progress will not be saved'))changePath("/", history)}}
                >
                  <Logo />
                </div>
                <h1 className={style.restaurantName}>{selected.Name}</h1>
              </div>
            </div>
            {/* Memory is used to navigate as we don't want to change URL each time */}
            <Router history={memoryHistory}>
              <Switch>
                <Route path="/details" component={() => <ContentContainer type="detail" />} />
                <Route path="/confirmation" component={() => <ContentContainer type="confirmation" />} />
                <Route path="/complete" component={() => <ConfirmedBooking history={history} />} />
                <Route path="/" component={() => <ContentContainer type="time" mainHistory={history} />} />
              </Switch>
            </Router>
          </div>
        )}

    </div>
  );
}
Example #21
Source File: router.jsx    From covid19Nepal-react with MIT License 6 votes vote down vote up
function Routes(props) {
  return (
    <Switch location={props.location}>
      <Route path="/" exact component={Home} key="1" />
      <Route path="/demographics" exact component={PatientDB} key="2" />
      <Route path="/deepdive" exact component={DeepDive} key="3" />
      <Route path="/links" exact component={Links} key="4" />
      <Route path="/faq" exact component={FAQ} key="5" />
      <Route path="/essentials" exact component={Resources} key="6" />
    </Switch>
  );
}
Example #22
Source File: route.js    From choerodon-front-base with Apache License 2.0 6 votes vote down vote up
Index = ({ match }) => (
  <Switch>
    <PermissionRoute
      exact
      path={match.url}
      component={Content}
      service={(type) => service[type] || []}
    />
    <Route path="*" component={NoMatch} />
  </Switch>
)
Example #23
Source File: App.js    From sofia-react-template with MIT License 6 votes vote down vote up
App = (props) => {
  return (
    <div>
      <ToastContainer/>
      <HashRouter>
        <Switch>
          <Route path="/" exact render={() => <Redirect to="/template/dashboard" />} />
          <Route path="/template" exact render={() => <Redirect to="/template/dashboard"/>}/>
          <PrivateRoute path="/template" dispatch={props.dispatch} component={LayoutComponent} />
          <Route path="/login" exact component={Login} />
          <Route path="/error" exact component={ErrorPage} />
          <Route path="/register" exact component={Register} />
          <Route component={ErrorPage}/>
          <Route path='*' exact={true} render={() => <Redirect to="/error" />} />
        </Switch>
      </HashRouter>
    </div>
  );
}
Example #24
Source File: Layout.js    From sofia-react-template with MIT License 6 votes vote down vote up
Layout = (props) => {
  return (
    <div className={s.root}>
      <div className={s.wrap}>
        <Header />
        <Sidebar />
        <main className={s.content}>
          <Breadcrumbs url={props.location.pathname} />
          <Switch>
            <Route path="/template" exact render={() => <Redirect to="template/dashboard"/>} />
            <Route path="/template/dashboard" exact component={Dashboard}/>
            <Route path="/template/typography" exact component={Typography} />
            <Route path="/template/tables" exact component={Tables} />
            <Route path="/template/notifications" exact component={Notifications} />
            <Route path="/template/ui-elements" exact render={() => <Redirect to={"/template/ui-elements/charts"} />} />
            <Route path="/template/ui-elements/charts" exact component={Charts} />
            <Route path="/template/ui-elements/icons" exact component={Icons} />
            <Route path="/template/ui-elements/maps" exact component={Maps} />
            <Route path='*' exact render={() => <Redirect to="/error" />} />
          </Switch>
        </main>
        <Footer />
      </div>
    </div>
  );
}
Example #25
Source File: AdminApp.jsx    From frontend with MIT License 6 votes vote down vote up
AdminApp = () => {
  const classes = useStyles();
  return (
    <Box display="flex" width={1} height="100%">
      <CssBaseline />
      <Drawer
        open
        variant="persistent"
        classes={{ paper: classes.drawer }}
        PaperProps={{ elevation: 4 }}
      >
        <Box className={classes.logo} display="flex" alignItems="center">
          <NavLink to="/">{logo}</NavLink>
        </Box>
        <AdminNavigation />
      </Drawer>
      <Box width={1} className={classes.main}>
        <AppBar position="relative" elevation={2}>
          <Toolbar />
        </AppBar>
        <Container className={classes.content}>
          <Box mt={2}>
            <Switch>
              <Route path="/admin/dashboard" component={DashboardPage} />
              <Route path="/admin/applications" component={ApplicationPage} />
            </Switch>
          </Box>
        </Container>
      </Box>
    </Box>
  );
}
Example #26
Source File: routes.jsx    From howlongistheline.org with Mozilla Public License 2.0 6 votes vote down vote up
renderRoutes = () => (
  // <Provider store={store}>
    <Router history={browserHistory}>
    <MuiPickersUtilsProvider utils={MomentUtils}>
    <CookiesProvider>
    <ToastContainer />
      <Switch>
        <Route exact path="/" component={Nearme} />
        <Route exact path="/addLine" component={AddLine} />
        <Route exact path="/editLine" component={EditLine} />
        <Route exact path="/shopDetails" component={ShopDetails} />
        <Route exact path="/feedback" component={FeedBack} />
        <Route exact path="/FAQ" component={faq} />
        <Route exact path="/learntocode" component={learntocode} />
        <Route exact path="/duplicated" component={duplicated} />
        <Route exact path="/stocks" component={Stocks} />
        <Route exact path="/editLocation" component={EditLocation} />
      </Switch>
      </CookiesProvider>
      </MuiPickersUtilsProvider>
    </Router>

  // </Provider>
)
Example #27
Source File: App.js    From create-magic-app with MIT License 6 votes vote down vote up
export default function App() {
  return (
    <BrowserRouter>
      <div className="App">
        <Switch>
          <Route path="/login" exact>
            <Login />
          </Route>

          <Route path="/callback" exact>
            <Callback />
          </Route>

          <Route path="*">
            <Profile />
          </Route>
        </Switch>
      </div>
    </BrowserRouter>
  );
}
Example #28
Source File: Layout.js    From light-blue-react-template with MIT License 5 votes vote down vote up
render() {
    return (
      <div
        className={[
          s.root,
          'sidebar-' + this.props.sidebarPosition,
          'sidebar-' + this.props.sidebarVisibility,
        ].join(' ')}
      >
        <div className={s.wrap}>
          <Header />
          {/* <Chat chatOpen={this.state.chatOpen} /> */}
          {/* <Helper /> */}
          <Sidebar />
          <Hammer onSwipe={this.handleSwipe}>
            <main className={s.content}>
              <BreadcrumbHistory url={this.props.location.pathname} />
              <TransitionGroup>
                <CSSTransition
                  key={this.props.location.key}
                  classNames="fade"
                  timeout={200}
                >
                  <Switch>
                    <Route path="/app/main" exact render={() => <Redirect to="/app/main/dashboard" />} />
                    <Route path="/app/main/dashboard" exact component={Dashboard} />
                    <Route path="/app/components/icons" exact component={UIIcons} />
                    <Route path="/app/notifications" exact component={UINotifications} />
                    <Route path="/app/components/charts" exact component={Charts} />
                    <Route path="/app/tables" exact component={TablesStatic} />
                    <Route path="/app/components/maps" exact component={MapsGoogle} />
                    <Route path="/app/typography" exact component={CoreTypography} />
                  </Switch>
                </CSSTransition>
              </TransitionGroup>
              <footer className={s.contentFooter}>
                Light Blue React Template - React admin template made by <a href="https://flatlogic.com" >Flatlogic</a>
              </footer>
            </main>
          </Hammer>
        </div>
      </div>
    );
  }
Example #29
Source File: PagesAndResources.jsx    From frontend-app-course-authoring with GNU Affero General Public License v3.0 5 votes vote down vote up
function PagesAndResources({ courseId, intl }) {
  const { path, url } = useRouteMatch();

  const dispatch = useDispatch();
  useEffect(() => {
    dispatch(fetchCourseApps(courseId));
  }, [courseId]);

  const courseAppIds = useSelector(state => state.pagesAndResources.courseAppIds);
  const loadingStatus = useSelector(getLoadingStatus);

  const { config } = useContext(AppContext);
  const learningCourseURL = `${config.LEARNING_BASE_URL}/course/${courseId}`;

  // Each page here is driven by a course app
  const pages = useModels('courseApps', courseAppIds);
  if (loadingStatus === RequestStatus.IN_PROGRESS) {
    return <></>;
  }

  return (
    <PagesAndResourcesProvider courseId={courseId}>
      <main className="container container-mw-md px-3">
        <div className="d-flex justify-content-between my-4 my-md-5 align-items-center">
          <h3 className="m-0">{intl.formatMessage(messages.heading)}</h3>
          <Hyperlink
            destination={learningCourseURL}
            target="_blank"
            rel="noopener noreferrer"
            showLaunchIcon={false}
          >
            <Button variant="outline-primary" className="p-2"> {intl.formatMessage(messages.viewLiveButton)}</Button>
          </Hyperlink>
        </div>

        <PageGrid pages={pages} />
        <Switch>
          <PageRoute
            path={[
              `${path}/discussion/configure/:appId`,
              `${path}/discussion`,
            ]}
          >
            <DiscussionsSettings courseId={courseId} />
          </PageRoute>
          <PageRoute path={`${path}/:appId/settings`}>
            {
              ({ match, history }) => {
                const SettingsComponent = React.lazy(async () => {
                  try {
                    // There seems to be a bug in babel-eslint that causes the checker to crash with the following error
                    // if we use a template string here:
                    //     TypeError: Cannot read property 'range' of null with using template strings here.
                    // Ref: https://github.com/babel/babel-eslint/issues/530
                    return await import('./' + match.params.appId + '/Settings.jsx'); // eslint-disable-line
                  } catch (error) {
                    console.trace(error); // eslint-disable-line no-console
                    return null;
                  }
                });
                return (
                  <Suspense fallback="...">
                    <SettingsComponent onClose={() => history.push(url)} />
                  </Suspense>
                );
              }
            }
          </PageRoute>
        </Switch>
      </main>
    </PagesAndResourcesProvider>
  );
}