How to use a React Router on top of a Rails router (without using a rocket gem)?

Now I am building a React application on top of a Ruby on Rails application (without a gem with a reactive lattice), using browserify-rails to compile js.

So I tried react-router in the application configuration router

This is my main.js

import React from 'react'; import ReactDOM from 'react-dom'; import { Router, Route } from 'react-router'; import { browserHistory } from 'react-router'; /*Import Component*/ import DashBoard from './components/dashboard'; import Group from './components/dashboard'; /* * * Routes * * */ var routes = ( <Router history={browserHistory}> <Route path="/" component={DashBoard}/> <Route path="/group" component={Group}/> </Router> ); ReactDOM.render(routes , document.querySelector('#main')); 

But when I go to

 http://my.app.dev/group 

I got

 No route matches [GET] "/group" (From Rails) 

So how can I fix this and make React Router on top of Rails a router?

Thanks!

+11
source share
2 answers

If you want to redirect your entire request to one page, this is easy:

 # config/routes.rb root 'dash_board#index' get '*path', to: 'dash_board#index' 

If Rails displays your React components on the DashBoard # index page, React router will hook it from there.

+27
source

You can also specify all the URLs you need in Router manually in route.rb, redirecting them to the rails controller using Router, say / home:

 # config/routes.rb Rails.application.routes.draw do root action: :index, controller: 'home' get 'url1', action: :index, controller: 'home' get 'url2', action: :index, controller: 'home' get 'url3', action: :index, controller: 'home' end 

Note that your underlying React component will use Router to use the corresponding component if you have something like:

 <Route path="/url1" component={ ComponentForUrl1 } /> <Route path="/url2" component={ ComponentForUrl3 } /> <Route path="/url3" component={ ComponentForUrl2 } /> 
0
source

All Articles