React router not rendering default route

Viewed 609

I am trying to add a default page where the user first goes to when opening the site, but it is not rendering the default route. How can I fix this? react router v6 Note: works fine without router so shouldnt be a component issue

import React, {useState} from 'react';
import './App.css';
import {BrowserRouter as Router, Routes, Route, Switch} from 'react-router-dom';
import AddNote from './components/noteDisplay/addNote/newNote.js'
import NoteDisplay from './components/noteDisplay/noteDisplay.js'
import secondPage from './components/secondPage/secondContainer.js'
const App = () => {

  return (
      
        <div className="App">
          <h1 className="app-title">My notes</h1>
          <Router>
            <div>
              <Routes>

                <Route path='/second' component={secondPage}/>
                <Route path='*' component={NoteDisplay}/>

              </Routes>
            </div>

          </Router>

        </div> 


  );
}


export default App;
2 Answers

The page user see first is the home page and specified with "/". To make it default you can use index prop of Route component like in the following

<Route path="/" element={<App />}>
    <Route index element={<Home />} />
    <Route path='/second' component={secondPage}/>
    <Route path='*' component={NoteDisplay}/>
</Route>

The react-router-dom v6 Route component API changed significantly from v5. Gone are the component prop and render and children function props, replaced by a single element prop that takes a ReactElement, a.k.a. JSX.

Routes & Route

declare function Route(
  props: RouteProps
): React.ReactElement | null;

interface RouteProps {
  caseSensitive?: boolean;
  children?: React.ReactNode;
  element?: React.ReactElement | null;
  index?: boolean;
  path?: string;
}

Switch from the old Route component prop to the element prop, and pass the routed component as JSX instead of a reference to the component.

<Routes>
  <Route path='/second' element={<SecondPage />} />
  <Route path='*' element={<NoteDisplay />} />
</Routes>

Edit react-router-not-rendering-default-route

Related