Home > Back-end >  Nested Routing Not Working in React Router v6
Nested Routing Not Working in React Router v6

Time:04-18

im trying to use nested routing with dynamic values . Normal Routes in App.js are working but the nested route in QouteDetail is not showing anything . console says that " NO ROUTES MATCHED LOCATION " . Can somebody tell me what's wrong.

CODE :

import React from 'react';
import {Route , Routes } from "react-router-dom";
import AllQuotes from './components/AllQuotes';
import NewQuote from './components/NewQuote';
import QuoteDetail from './components/QuoteDetail';

function App() {
  return (
    <div>
      <Routes>
        <Route path="/" element={<AllQuotes/>} />
        <Route path="/quotes" element={<AllQuotes/>} />
        <Route path="/new-quotes" element={<NewQuote/>} />
        <Route exact path="/quotes/:quoteID" element={<QuoteDetail/> } /> 
      </Routes>

    </div>
  );
}

export default App;
import React from 'react';
import { Route, Routes , useParams } from 'react-router-dom';
import Comments from './comments/Comments';

function QuoteDetail(props) {
    const params = useParams();
    return (
        <div>
            <h1>QUOTE DETAILS</h1>
            <h2>{params.quoteID}</h2>

            <Routes>
            <Route exact path={`/quotes/${params.quoteID}/comments`}  element= {<Comments/>} />  
            </Routes> 
        </div>
    );
}

export default QuoteDetail;

CodePudding user response:

I don't know why you need to create route in another functional component, you can create nested routes in App.js with react router 6:

<Routes>
...
  <Route path="/quotes/:quoteID" element={<QuoteDetail/> }>
    <Route path="/quotes/:quoteID/coments" element={<Comments/>} />
  </Route>
</Routes>

CodePudding user response:

The parent route path has no trailing "*". This means if you navigate deeper, the parent won't match anymore and therefore the child routes will never render.

You should change:

<Route path="/quotes/:quoteID" element={<QuoteDetail/> } /> 

to:

<Route path="/quotes/:quoteID/*" element={<QuoteDetail/> } /> 
  • Related