DEV Community

Stanislav Kniazev
Stanislav Kniazev

Posted on

Native Rails Support for React and Redux with Superglue lib

Rails 7 introduced progressive client-side interactivity tools such as Hotwire, Turbo, and Stimulus in 2021, making it a suitable option for developing applications with easy or medium complexity.
If you prefer to use your favorite React + Redux stack, you would need to build an API, set up routing, and integrate your client and server in a classic way.

Here comes Superglue lib (https://github.com/thoughtbot/superglue) that allows to use classic Rails approach to build rich React+Redux applications without API and client-side routing.

It works through 3 familiar templates, for example:

  • products.json.props A presenter written in a jbuilder-like template that builds your page props.
  • products.js Your page component that receives the props from above.
  • products.html.erb Injects your page props into Redux when the browser loads it. So, props looks like this:
json.header do 
  json.username @user.username 
  json.linkToProfile url_for(@user) 
end 
json.products do 
  json.array! @products do |product| 
    json.title product.title 
    json.urlToProduct url_for(product) 
    end 
  end 
end
Enter fullscreen mode Exit fullscreen mode

Then you can use it in your React components:

import React from 'react' 
import { useSelector } from 'react-redux' 
import { Header, Footer, ProductList } from './components' 

export default function FooBar({ 
    header, 
    products = [], 
    productFilter, 
    footer 
}) { 
  const flash = useSelector((state) => state.flash) 
  return ( 
    <> 
        <p id="notice">{flash && flash.notice}</p> 
        <Header {...header}> ... </Header> 
        <ProductList {...products}> 
            <ProductFilter {...productFilter} /> 
        </ProductList> 
        <Footer {...footer} /> 
    </> 
  ) 
}
Enter fullscreen mode Exit fullscreen mode

It is build on top of Turbolinks 3, but instead of sending your products.html.erb over the wire and swapping the <body>, it sends products.json.props over the wire to your React and Redux app and swaps the page component.

It also offers UJS helpers that can be utilized with your React components for SPA transitions.

This approach seems promising to me - I'm eager to see how it evolves in the future.

If anyone already tried, please share your expierence.

Docs, more information and examples:
https://github.com/thoughtbot/superglue
https://thoughtbot.github.io/superglue/#/
https://github.com/thoughtbot/select-your-own-seat-superglue (example app)

Top comments (0)