DEVELOPMENT by Pedro Resende

Ruby On Rails with React.js frontend Integration

with tailwindcss

Post by Pedro Resende on the 2 of December of 2023 at 10:00

Tags: devdevelopmenttutorialcsstailwindcssrorrailsrubyRuby-On-Rails

header

A few years ago, I've dedicated a post to the integration of React.js with Symfony (Symfony with React.js frontend Integration).

Therefore, I've decided, like I've done 7 years ago with React.js to write a possible integration with Ruby On Rails.

A kind reminder that this is a possible integration and if any of you believe there is a better approach, please feel free to leave a comment.

Let's start by installing a clean Rails 7.1.2 environment for this example:

rails new rails_project_with_react --javascript=esbuild --css=tailwind

Now that we have our rails app properly setup, let's add react, by running the following

cd rails_project_with_react
yarn add react react-dom

Now, create a new folder called components under, app/javascript.

mkdir -p app/javascript/components

inside, let's create two files, the first index.tsx with the following

import React from "react"
import { createRoot } from "react-dom/client"
import Home from "./Home"

document.addEventListener("turbo:load", () => {
  const root = createRoot(
    document.body.appendChild(document.getElementById("react")!)
  )

  root.render(<Home />)
})

the second, called Home.tsx and add

import React from "react"

const Home = () => {
  return <div className="mx-4 container text-2xl">Welcome Home</div>
}

export default Home

finally, open app/javascript/application.js and add

import "./components"

Now, let's add a new controller called base to have our view

rails g controller base index

if you open the file, you should have the following

class BaseController < ApplicationController
  def index
  end
end

finally, open the view file, app/views/base/index.html.erb, and add the following

<h1>Base#index</h1>
<p class="text-xl">Find me in app/views/base/index.html.erb</p>

<div id="react"></div>

to allow tailwindcss to work properly with react, we need to open the tailwind.config.js files, in the root folder and add to the content array

"./app/javascript/**/*.tsx"

boot up your rails app by running

./bin/dev

and open your browser on http://localhost:3000. You should have the following.

header

That is it, please let me know if you propose a different approach, the code is available at this link.