3

I am using "react-scripts": "4.0.2" and all my components are React Hooks. My logic involves nested routing but the end result is not rendered.

Body.js:

<Switch>
    <Route path="/form" exact component={Forms}></Route>
    <Route path="/" exact component={ShopCards}></Route>
</Switch>

Forms.js:

const expandFormHandler = (pid) => {
console.log("PID:" + pid);           //It is printing correcly
props.history.push({ pathname: "/form/" + pid });  //URL is also changing accordingly
}

return (
<div>
  {prodCards.map((card, index) => (
    <ProductCard
      key={index}
      expand={expandFormHandler.bind(this, card.pid)}
    />
  ))}

  <Route path={props.match.url + "/:id"} exact component={Modal} />
//<Route path="/form/:id" exact component={Modal} />   //Tried this too
</div>
  );

Modal.js:

<h1>{props.match.params.id}Hello</h1>

The modal is not rendering even it's useEffect() is not executed.

Now if I place Modals Route in Body.js like following the Modal is rendered but not in the same page below ProductCard

<Switch>
    <Route path="/form" exact component={Forms}></Route>
    <Route path="/form/:id" exact component={Modal} />
    <Route path="/" exact component={ShopCards}></Route>
</Switch>
2
  • 1
    Can you clarify what is your goal? You want to show Modal component on the same page with Forms component if url contains :id? Commented Feb 12, 2021 at 8:44
  • if you want modal on the same page with the ProductCard. I don't think using route like that can achieve it. Commented Feb 12, 2021 at 8:49

1 Answer 1

3

Issue

The Route rendering Forms is using an exact match, i.e. when the path is exactly "/form"

<Switch>
  <Route path="/form" exact component={Forms}></Route> // <-- exact match!!
  <Route path="/" exact component={ShopCards}></Route>
</Switch>

When the path is any subroute, i.e. "/form/3" it is no longer an exact match and Form is no longer rendered.

Solution

Remove the exact prop from the root route.

<Switch>
  <Route path="/form" component={Forms}></Route> // <-- general match
  <Route path="/" exact component={ShopCards}></Route>
</Switch>

Forms.js

return (
  <div>
    {prodCards.map((card, index) => (
      <ProductCard
        key={index}
        expand={expandFormHandler.bind(this, card.pid)}
      />
    ))}

    <Route path="/form/:id" component={Modal} /> // <-- more specific match
  </div>
);
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.