Home > OS >  SyntaxError: Expected corresponding JSX closing tag for <Route> with react-router-dom v6
SyntaxError: Expected corresponding JSX closing tag for <Route> with react-router-dom v6

Time:05-11

I want my react app to have urls that look like localhost:3000/projects/construction and localhost:3000/services/landscape.

The docs for react-router-dom say you can nest routes like so:

function App() {
  return (
    <Routes>
      <Route path="invoices" element={<Invoices />}>
        <Route path="sent" element={<SentInvoices />} />
      </Route>
    </Routes>
  );
}

Why then does my app fail with an Expected corresponding JSX closing tag for <Route> error when I do this?

<BrowserRouter>
 <Routes>
  <Route index element={<Home />} />
  <Route path='/projects' element={<Projects />}>
   <Route path='/construction' element={<Construction />}>
  </Route>
  <Route path='/services' element={<Services />}>
   <Route path='/landscape' element={<Landscape />}>
  </Route>
  <Route path='/about' element={<About />} />
  <Route path='/contact' element={<Contact />} />
  <Route path='*' element={<Navigate to='/' replace />} />
 </Routes>
</BrowserRouter>

CodePudding user response:

The Services and Landscape routes are missing the closing tag. They can self-close, or have the closing tag added.

<BrowserRouter>
  <Routes>
    <Route index element={<Home />} />
    <Route path="/projects" element={<Projects />}>
      <Route path="/construction" element={<Construction />}></Route>
      <Route path="/services" element={<Services />} />   // <-- close
      <Route path="/landscape" element={<Landscape />} /> // <-- close
    </Route>
    <Route path="/about" element={<About />} />
    <Route path="/contact" element={<Contact />} />
    <Route path="*" element={<Navigate to="/" replace />} />
  </Routes>
</BrowserRouter>
  • Related