Welcome to the Treehouse Community

Want to collaborate on code errors? Have bugs you need feedback on? Looking for an extra set of eyes on your latest project? Get support with fellow developers, designers, and programmers of all backgrounds and skill levels here with the Treehouse Community! While you're at it, check out some resources Treehouse students have shared here.

Looking to learn something new?

Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and join thousands of Treehouse students and alumni in the community today.

Start your free trial

JavaScript React Router 4 Basics Navigating, Nesting and Redirecting Routes Redirecting a Route

Dawid Jacobs
seal-mask
.a{fill-rule:evenodd;}techdegree seal-36
Dawid Jacobs
Full Stack JavaScript Techdegree Graduate 17,835 Points

Redirecting in React-Router V6 Solution

For those of you who are trying to follow along with V6 of React-router.

<Redirect /> has been removed since V6, so the suggested work around is to use the the <Navigate replace to /> component for initial rendering. Just note this won't redirect when doing server side rendering. (I'll link the notes provided below that has the solution for that as well.)

My App.js file

import React from 'react';
import {
  BrowserRouter,
  Routes,
  Route,
} from "react-router-dom";

//App components
import Home from './Home'
import About from './About'
import Header from './Header'
import Teachers from './Teachers'
import Courses from './Courses'



const App = () => (

  <BrowserRouter>
    <div className="container">
      <Header />
      <Routes>
        <Route exact path="/" element={ <Home />} />
        <Route path="/about" element={ <About title="About" />} />
        <Route path="/teachers" element={ <Teachers />} />
    {/*  *included after /courses/ to extend the root from the Courses.js file ... */}
        <Route path="/courses/*" element={ <Courses />} />
      </Routes>
    </div>
  </BrowserRouter>
);

export default App;

Snipped from my Courses.js file

      <Routes>
    {/*  Redirected route ... */}
        <Route path="/" element={<Navigate replace to="/courses/html" />} />
    {/*  normal routes forming part of the /courses/* route from the App.js file ... */}
        <Route path="/html" element={ <HTML />}>HTML</Route>
        <Route path="/css" element={ <CSS />}>HTML</Route>
        <Route path="/javascript" element={ <JavaScript />}>HTML</Route>
      </Routes>
  </div>

Link to the React-Router V6 notes regarding Redirecting: https://gist.github.com/mjackson/b5748add2795ce7448a366ae8f8ae3bb

Hope it saves you some time!

2 Answers