Yhunie-the-cat
Yhunie-the-cat

Reputation: 38

React routing link from nested component

I want to add routing to my app but the "Link" I made in a child component doesn't work onClick, but only when I refresh the page. I guess the problem is the way too much nesting but I have no idea how can I solve it.

One mention: I imported BrowserRouter as Router everywhere.

This is the file structure

This is the code spippets that related to my problem:

App component:

   function App() {
  return (
    <Router >
      <div className="App">
        <Switch>
          <Route exact path="/" component={NewFetch} />
          <Route path="/cardID/:id" component={Details} />     //The route that doesn't work
        </Switch>
      </div>
    </Router>

NewFetch (Main) component:

<Router> //Tried with <React.Fragment>
...
   <Route path={["/cards/:name", "/cards/:filter"]}>
      <Filter isLoaded={isLoaded} handleScroll={handleScroll} toScrollTop={toScrollTop} value={value} 
         scrollPosition={scrollPosition} jumpToTop={jumpToTop} testFilter={testFilter} />
   </Route>
</Router>

Card (child 2) component from :

const Card = (props) => {
  return (
    <div className={props.img ? "card" : "hide"}>
      <Link to={`/cardID/id=${props.id}`} >          //Link that doesn't connect
        <img src={props.img} alt={props.name} />
      </Link>
    </div>
  )
};

So basically I can't connect the "Link" from a hardly nested component.

Upvotes: 0

Views: 757

Answers (1)

Ntshembo Hlongwane
Ntshembo Hlongwane

Reputation: 1051

function App() {
  return (
    <Router >
      <div className="App">
        <Switch>
          <Route exact path="/" component={NewFetch} />
          <Route path="/cardID/:id" component={Details} />     //The route that doesn't work
        </Switch>
      </div>
    </Router
const Card = (props) => {
  return (
    <div className={props.img ? "card" : "hide"}>
      <Link to={`/cardID/id=${props.id}`} >          //Link that doesn't connect
        <img src={props.img} alt={props.name} />
      </Link>
    </div>
  )
};

Above is your code which might look right but the is a slight bug here:

  • The bug is in the wrong way you are linking to path="/cardID/:id

  • What you are to do is in your Card child2 is:

const Card = (props) => {
  return (
    <div className={props.img ? "card" : "hide"}>
      <Link to={`/cardID/${props.id}`} > //Removed **id=....**
        <img src={props.img} alt={props.name} />
      </Link>
    </div>
  )
};
  • This is what you have to understand that when you make a route like so path="/route/:id" the :id is just a placeholder waiting for you to place anything so id is commonly used so your code makes sense and mainly basically you want to route based on id but one could have written :cat for example but that is just a placeholder

Upvotes: 1

Related Questions