Can't manage to make page to specific route

Viewed 25

Here is the app component:

  return (
    <BrowserRouter>
      <div className="flex  border-2 border-grey flex-col max-w-4xl min-h-screen mx-auto">
        <Navigation />
        <MainContainer>
          <Switch>
            <Route exact path="/">
              <Home />
            </Route>
            <Route>
              <CreateBlog path="/create" />
            </Route>
            <Route>
              <FullBlogDetails path="/blogs/:id" />
            </Route>
          </Switch>
        </MainContainer>
      </div>
    </BrowserRouter>
  );
}

The problem is that each time I click a blog, it redirects me to "/create", instead of "/blogs/:id".

Here is the Link that does the navigation:

<Link
  to={`/blogs/${id}`}
  key={id}
  className="p-4 flex border-2 border-grey-200 items-center hover:shadow-lg my-6"
>
  <div>
    <img className="h-20" src={picture} />
    <p className="">
      Written by{" "}
      <span className="text-rose-500 font-bold text-lg">
        {firstName + " " + lastName}
      </span>
    </p>
  </div>
  <p className="font-bold">"{title}..."</p>
</Link>

The weird part is that if I swap the "/create" Route with "/blogs/:id" Route, making it third, the app only shows the "/blogs/:id" and then "/create" doesn't show now. Basically the third route doesn't work.

1 Answers

You've incorrectly placed the path prop for the routes on the routed component instead of the Route component. The Switch component only renders the first matching Route or Redirect and so a Route sans the path prop will always match. Since the route for both "/create" and "/blogs/:id" is missing the path prop it makes sense that swapping their order and trying to navigate to the second still matches and renders the first.

Move the path prop to the Route component. I suggest also ordering the routes in inverse order of path specificity so more specific paths are rendered before less specific paths. This generally omits the need to specify the exact prop.

Example:

<BrowserRouter>
  <div className="flex  border-2 border-grey flex-col max-w-4xl min-h-screen mx-auto">
    <Navigation />
    <MainContainer>
      <Switch>
        <Route path="/create">    // <-- path on route
          <CreateBlog />
        </Route>
        <Route path="/blogs/:id"> // <-- path on route
          <FullBlogDetails />
        </Route>
        <Route path="/">          // <-- path on route
          <Home />
        </Route>
      </Switch>
    </MainContainer>
  </div>
</BrowserRouter>
Related