Khalil Nazari
Khalil Nazari

Reputation: 3

ReactJS and Laravel, nested route is not working. It bring me to the same page

I'm developing a blog using Laravel 7 and ReactJS. I have a /blog page and for each blog I have a post. The post should be displayed in /blog/post/1 type, but this routing is not working: it returns to the /blog page. I'm not sure if the problem is with react routing or Laravel routing.

My route in web.php, Laravel:

Route::view('/{path?}', 'react');

My route in App.js file, ReactJS :

<Router> 
  <Switch>
    <Route exact path="/" component={Home} />
    <Route path="/blog" component={Blog} />
    <Route path="/blog/post/:id" component={Post} />
    <Route path="*" component={notfound} />
</Switch> 
</Router>

Link on /blog page to view a post with id 12

<Link to="/blog/post/12">React More</Link>

When I click the above link it brings me again to /blog page.

Upvotes: 0

Views: 435

Answers (1)

jpmc
jpmc

Reputation: 1193

The routes are prioritised by order. So the order you have them in matters. You could do:

<Router> 
  <Switch>
    <Route exact path="/" component={Home} />
    <Route path="/blog/post/:id" component={Post} />
    <Route path="/blog" component={Blog} />
    <Route path="*" component={notfound} />
</Switch> 
</Router>

Or by using the 'exact' keyword like you did for the / route, so it has to be an exact match.

<Router> 
  <Switch>
    <Route exact path="/" component={Home} />
    <Route exact path="/blog" component={Blog} />
    <Route path="/blog/post/:id" component={Post} />
    <Route path="*" component={notfound} />
</Switch> 
</Router>

Upvotes: 1

Related Questions