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

ericchapman

Eric The Coder

Posted on April 15, 2021

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

💖 💪 🙅 🚩
ericchapman
Eric The Coder

Posted on April 15, 2021

Join Our Newsletter. No Spam, Only the good stuff.

Sign up to receive the latest update from our blog.

Related