skip to Main Content

I want to display Quiz component content with path "/quiz" after I click button
and fetch component with path "/"

App jsx file:

 <Router>
        <Routes>
          <Route path="/" element={<Fetch />} />
          {/* <Route path="/quiz" element={<Quiz />} /> */}
        </Routes>
      </Router>

Fetch jsx file

    <>
      {[...new Set(catData.map((c) => c.category))].sort().map((cat) => (
        // <Quiz cat={cat} setChoosenCat={setChoosenCat} choosenCat={choosenCat} />
        <div key={cat}>
          <Link to="/quiz" >
            <p onClick={() => handleClick(cat)}>{cat}</p>
          </Link>
        </div>
      ))}

      <Routes>
        {isClicked  && (
          <Route
            path="/quiz"
            element={
              <Quiz data={data}/>
            }
          />
        )}
      </Routes>

    </>

  

when I do this, the page route is change to /quiz but the page is empty and this error shows

No routes matched location "/quiz" 

2

Answers


  1. you have the route commented out

     {/* <Route path="/quiz" element={<Quiz />} /> */}
    

    remove the {/* at both ends or just replace that line with the following

    <Route path="/quiz" element={<Quiz />} />
    
    Login or Signup to reply.
  2. It seems like the issue is with the conditional rendering of the Route component inside the Fetch component. Since Routes are evaluated in order, when you click the link to "/quiz", the first Route with path="/" is matched, and it renders its associated element prop ().

    To resolve this, you need to adjust the route hierarchy and ensure that the Route for "/quiz" is rendered outside of the Fetch component. Here’s an approach to fix this:

    <Router>
      <Routes>
        <Route path="/" element={<Fetch />} />
        <Route path="/quiz" element={<Quiz data={data} />} />
      </Routes>
    </Router>
    

    In the Fetch component, remove the nested Routes block and the conditional rendering of the Route:

    <>
      {[...new Set(catData.map((c) => c.category))].sort().map((cat) => (
        <div key={cat}>
          <Link to="/quiz">
            <p onClick={() => handleClick(cat)}>{cat}</p>
          </Link>
        </div>
      ))}
    </>
    

    This way, when you click on the link , it should render the Quiz component associated with the "/quiz" route directly without conditional rendering inside the Fetch component. Adjust the Quiz component’s props and behavior as needed to handle the data passed to it.

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search