Home > Mobile >  How do I redirect from a root path to another root path and still render sub-routes?
How do I redirect from a root path to another root path and still render sub-routes?

Time:12-11

import React from 'react';
import { BrowserRouter as Router, Route, Switch, Redirect } from 'react-router-dom';
import Footer from './components/Footer';
import NavMenu from './components/NavMenu';
import ScrollToTop from './components/ScrollToTop';
import About from './pages/About';
import Contact from './pages/Contact';
import Home from './pages/Home';
import Projects from './pages/Projects';
import Gallery from './pages/Gallery';


export default function App() {
  return (
    <>
      <Router>
        <NavMenu />
        <ScrollToTop />
        <Switch>
          <Route path="/about">
            <About />
          </Route>
          <Route path="/contact">
            <Contact />
          </Route>
          <Route path="/projects">
            <Projects />
          </Route>
          <Route path="/gallery/">
            <Redirect to="/projects" />
            <Gallery />
          </Route>
          <Route path="/">
            <Home />
          </Route>
        </Switch>
        <Footer />
      </Router>
    </>
  );
}

The problem is that I want it to redirect (example.com/gallery) to (example.com/projects) but let me use something like (example.com/gallery/photo1) without redirect as well to (example.com/projects)

CodePudding user response:

You can use the exact prop to specify an exact path.

<Route exact path="/gallery/">
  <Redirect to="/projects" />
  <Gallery />
</Route>

CodePudding user response:

Render two separate routes, one to redirect from "/gallery" to "/projects", and the other for a specific gallery.

Example:

export default function App() {
  return (
    <>
      <Router>
        <NavMenu />
        <ScrollToTop />
        <Switch>
          <Route path="/about">
            <About />
          </Route>
          <Route path="/contact">
            <Contact />
          </Route>
          <Route path="/projects">
            <Projects />
          </Route>
          <Route path="/gallery/:galleryId">
            <Gallery />
          </Route>
          <Redirect from="/gallery" to="/projects" />
          <Route path="/">
            <Home />
          </Route>
        </Switch>
        <Footer />
      </Router>
    </>
  );
}
  • Related