React-router-dom displays nothing when using 'Route'

Viewed 768

I am trying to render an ultra-simple webpage using react-routing-dom lib. Here is my app.js

import React from 'react';
import Nav from './nav.js';
import Shop from './shop.js';
import About from './about.js';
import { BrowserRouter as Router, Route, Routes } from 'react-router-dom';

import './App.css';

function App() {
  return (
    <>
    <Nav />
    <Router>
      <Route exact path='/' element={<About />} />
      <Route exact path='/shop' element={<Shop />} />
    </Router>
    </>
  );
}

export default App;

using this, I run npm start and expect that the <Nav /> and <About /> components render at http://localhost:3000. Instead, the screen is completely blank. There are no warnings, errors, etc.; it's a clean build. Not even the <Nav /> component that is outside the entire Router block is rendered!

The plot thickens: when I build and run the following, all three components render.

import React from 'react';
import Nav from './nav.js';
import Shop from './shop.js';
import About from './about.js';
import { BrowserRouter as Router, Route, Routes } from 'react-router-dom';

import './App.css';

function App() {
  return (
    <>
    <Nav />
    <Router>
      <About />
      <Shop />
    </Router>
    </>
  );
}

export default App;

From this, I think its safe to assume that <Route /> is the problem.

react-router-dom seems to change a lot in a relatively short amount of time, so there is a lot of outdated info. If someone could point me in the right direction, I would be very grateful indeed.

2 Answers

Only thing I see missing is the Routes component wrapping the Route components. You imported Routes but don't appear to have used it. All Route components must be rendered into a Routes component (or another Route if nesting). Without the Routes you should be seeing the 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>.

<Router>
  <Routes>
    <Route exact path="/" element={<About />} />
    <Route exact path="/shop" element={<Shop />} />
  </Routes>
</Router>

Edit react-router-dom-displays-nothing-when-using-route

Check if you have installed react-router-dom version 6. for version 6 you must wrap up all 'Route' inside a "Routes".

Related