Home > front end >  React Router - never rendered directly
React Router - never rendered directly

Time:08-02

in my react app routing is not working and it throws an error in the console. in my index file

import { BrowserRouter as Router, Route } from 'react-router-dom';

<React.StrictMode>
    <Router>
      <Route path="/" element={<App />} />
    </Router>
  </React.StrictMode>

and in my App.js

import { Route, Routes, useHistory } from 'react-router-dom'; 

function App() {
  return (
    <div className="App">
        {/* <DataProvder> */}
        <Sidebar />
        <Routes>
          <Route path='/' element={<Home />} />
          <Route path='/students' element={<Students />} />
          <Route path='/schools' element={<Schools />} />
          <Route path='/campus' element={<Campus />} />
          <Route path='/placement' element={<Placement />} />
          <Route path='/courses' element={<Courses />} />
          <Route path='/staff' element={<Staff />} />
        </Routes>
        {/* </DataProvder> */}
    </div>
  );
}

export default App;

When running this there is nothing to display, but in the console it throws this error:

Uncaught Error: A <Route> is only ever to be used as the child of <Routes> element, never rendered directly. Please wrap your <Route> in a <Routes>.

What am I doing wrong here?

CodePudding user response:

The <Route> in index.js needs wrapping with <Routes>

CodePudding user response:

All Route components must be rendered by either a Routes component or another Route component in the case of nesting routes.

The Route in the index.js file is wrapped and rendered by the Router which is invalid. To resolve wrap it in a Routes component.

import { BrowserRouter as Router, Routes, Route } from 'react-router-dom';

<React.StrictMode>
  <Router>
    <Routes>
      <Route path="/" element={<App />}/>
    </Routes>
  </Router>
</React.StrictMode>

Or just render App directly since it handles rendering Home on path "/" for you.

import { BrowserRouter as Router } from 'react-router-dom';

<React.StrictMode>
  <Router>
    <App />
  </Router>
</React.StrictMode>
  • Related