DEV Community

Cover image for Rails link to React (No API). Yes that's possible!
Eric The Coder
Eric The Coder

Posted on

Rails link to React (No API). Yes that's possible!

Rails link to React (No API) Yes that's possible

Everyone will agree that Rails and React combo are a powerful duo! But we all know that building and linking a backend and a frontend take time and resource. Not anymore...

Discover Inertia.js: Inertia is not another javascript framework. Inertia is glue code that easily bring React and Rails together like they was one!

Once setup completed, using inertia is very simple, easy and intuitive.

Imagine be able to render a React component from Rails with a classic render:

The routing is still manage by Rails (Yeah!):

root 'home#show'
Enter fullscreen mode Exit fullscreen mode

Rails home controller:

def show
  # Rails will render a React Component with props!
  render inertia: 'Hello',
    props: {
      name: 'Mike Taylor'
    }
end
Enter fullscreen mode Exit fullscreen mode

React Hello component

function Hello(props) {
  return <h1>Hello {props.name}</h1>
}

export default Hello
Enter fullscreen mode Exit fullscreen mode

Result
react-rails

Of course we could had send something more complex than a string. It is also easy to return database data. Example:

def show
    event = Event.find(params[:id])

    render inertia: 'Event/Show',
      props: {
        event: event.as_json(
          only: [ :id, :title, :start_date, :description ]
        )
      }
  end
Enter fullscreen mode Exit fullscreen mode

Ok you got my attention. So what exactly is Inertia?

With Inertia you build apps just like you've always done with your server-side web Rails framework. You use Rails existing functionality for routing, controllers, middleware, authentication, authorization, data fetching, and more.

The only thing that's different is your view layer. Instead of using server-side rendering (eg. ERB templates), the views are JavaScript page components. This allows you to build your entire front-end using React, Vue or Svelte.

Inertia also have option for server side rendering, forms helper, modal helper, validation helper and more.

How can I install and try Inertia?

Create a new rails app with React pre-configure

rails new demo --webpack=react
cd demo
npm install @inertiajs/inertia @inertiajs/inertia-react
Enter fullscreen mode Exit fullscreen mode

Add into Gemfile

gem 'inertia_rails'
Enter fullscreen mode Exit fullscreen mode

Install GEM

bundle install
Enter fullscreen mode Exit fullscreen mode

Add to 'app/javascript/packs/application.js'

import { App } from '@inertiajs/inertia-react'
import React from 'react'
import { render } from 'react-dom'

const el = document.getElementById('app')

render(
  <App
    initialPage={JSON.parse(el.dataset.page)}
    resolveComponent={name => require(`./Pages/${name}`).default}
  />,
  el
)
Enter fullscreen mode Exit fullscreen mode

Create a React component:
app/javascript/packs/Pages/hello.js

import React from 'react'

function Hello(props) {
  return <h1>Hello {props.name}</h1>
}

export default Hello
Enter fullscreen mode Exit fullscreen mode

Then create your route:
config/routes.rb

Rails.application.routes.draw do
  root 'home#show'
end
Enter fullscreen mode Exit fullscreen mode

Create home controler

rails g controller home
Enter fullscreen mode Exit fullscreen mode
class HomeController < ApplicationController
    def show
        render inertia: 'Hello',
          props: {
            name: 'Mike Taylor'
          }
    end
end
Enter fullscreen mode Exit fullscreen mode

Run your rails app

rails s
Enter fullscreen mode Exit fullscreen mode

What's next

For complete detail info about Inertia visit there web site at: https://inertiajs.com/

Inertia.js position himself to be a serious and powerful alternative to api. Of course usage in a real big project need to be tested and like everything else, I guess, some limitations will rise. For now the first impression is more than good and the team behind Inertia.js is professional and seem here for the long run.

Conclusion

That's it for this Inertia.js introduction. If you want me to do more inertia post let me know and let me know what you would like me to test?

I am new on twitter so if you want to make me happy
Follow me!: Follow @justericchapman

Top comments (4)

Collapse
 
amani_art profile image
Austine Amani

Love it šŸ˜. As someone who loves rails but have a great distaste for ERB, i find myself choosing Next.js every time with rails backend. This simplifies my previous attempt to use react in rails stack. Love it

Collapse
 
leastbad profile image
leastbad

@jaredcwhite is 100% correct. React ends up getting used to do things that other techniques are far better suited to. To me, the original sin of API-first development patterns is that you're taking on this massive unnecessary technical burden, which is keeping track of and synchronizing state between the client and the server.

Would you not be happier (and done faster) if you used a tool like StimulusReflex which allow you to maintain your state on the server, while delivering reactive updates in response to user activity?

Collapse
 
codewander profile image
Kanishka

Have you used this for a while? Can you provide an update on any limitations that you have observed?

Collapse
 
redbar0n profile image
Magne