Using JSX in Rails 7?

I’m used to earlier versions of Rails, and am making a new Rails 7 app. I want to use JSX in my code so I can write React elements directly in the Javascript.

Previously, I just had file.js.jsx files in my /assets/javascripts directory and the react-rails gem just made it work.

I’ve read a bunch of tutorials but they suggest either 1) using import maps (not really what I want here for JSX) or 2) essentially compiling your JSX with a watcher while developing, and then somehow also getting it to compile for the asset pipeline.

Do you have suggestions on how to do what I was doing previously? Rails makes .scss files “just work” and I am looking to do the same with .jsx files.

Also, is there an example React+JSX app I can look at somewhere see how everything is typically set up?

Thanks!

2 Likes

I have a rails 7 application - maybe it can shed some light on how you can use esbuild for this.

I mount tsx components: app/javascript/components/hello.tsx

and the application.js is here: app/javascript/application.js

by the way I used tsx for the demo because if you can mount tsx components, then jsx just works.

I would suggest using esbuild with the jsbundling-rails gem which has out of the box support for jsx. Alternatively, you can use rollup or manually set up webpack with the gem if you want.

from what I understand the successor to Webpacker for Rails 6 is Shakapacker for Rails 7. It has great out of the box configuration for webpack using Rails 7 and will handle your JSX/Typescript compilation needs.

I was introduced two weeks ago to something that looked like very promising.

ViteJS - https://vitejs.dev/

There is a gem to help the integration with Ruby on Rails:

Also, there’s this tool that helps integrate your frontend lib (React or anyother) with your backend without the need of creating an API.

Nice article to start reading:

Happy coding!

Thanks Fernando! If then also replace react by svelte there is a tutorial That all are rarely used tools, currently, see Stackoverflow Trends react-vs-svelte or npm trends vite-vs-webpack but they all are looking very promising