Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

react-router mounts the wrong component

I'm writing a React-on-Rails (v. 5) app and am running into an issue. When I visit the path accounts/:account_id/letters/new, React-Router is mounting the EmailShowComponent, when I want it to mount the EmailSendComponent.

This is my app.js file:

<Router history={browserHistory}>
  <Route path="/accounts/:id" component={AccountShowContainer} />
  <Route path="/accounts/:account_id/letters/:id" component={EmailShowComponent} />
  <Route path="/accounts/:account_id/letters/new" component={EmailSendComponent} />
</Router>

This is my main.js file:

import 'babel-polyfill';
import React from 'react';
import ReactDOM from 'react-dom';
import App from './App';

$(function(){
ReactDOM.render(
  <App />,
  document.getElementById('app')
  )
});

And I've placed "<div id="app">" tags inside each of the relevant html pages that generate those paths for the router.

Any idea what could be causing this?

like image 568
John Avatar asked Mar 09 '23 04:03

John


1 Answers

The problem is that the path /accounts/:account_id/letters/new also satisfies the path /accounts/:account_id/letters/:id. The difference being id gets to be "new".

To fix this, simply swap the order of your routes:

<Router history={browserHistory}>
  <Route path="/accounts/:id" component={AccountShowContainer} />
  <Route path="/accounts/:account_id/letters/new" component={EmailSendComponent} />
  <Route path="/accounts/:account_id/letters/:id" component={EmailShowComponent} />
</Router>

For more info, check out the Precedence section from the official docs:

Finally, the routing algorithm attempts to match routes in the order they are defined, top to bottom. So, when you have two sibling routes you should be sure the first doesn't match all possible paths that can be matched by the later sibling. For example, don't do this:

<Route path="/comments" ... />
<Redirect from="/comments" ... />
like image 159
Chris Avatar answered Mar 25 '23 01:03

Chris