Preact integration for Ruby on Rails.
- Add
webpackerandpreact-railsto your Gemfile
gem 'webpacker'
gem 'preact-rails'
- Install the gems by running
bundle install - Install Preact by running
yarn add preact - To transpile JSX, you need a Babel plugin that converts it to valid JavaScript code. Install @babel/plugin-transform-react-jsx by running
yarn add --dev @babel/plugin-transform-react-jsxOnce installed, you need to specify the function for JSX that should be used. Your .babelrc/babel.config.js should include the following plugin description{ "plugins": [ ["@babel/plugin-transform-react-jsx", { "pragma": "h", "pragmaFrag": "Fragment", }] ] } - Install the Preact UJS driver by running
yarn add preact_ujsornpm i preact_ujs - Include your Preact components in your application.js
Update
app/javascript/packs/application.js, add the following lines:var componentRequireContext = require.context("components", true); var PreactRailsUJS = require("preact_ujs"); PreactRailsUJS.useContext(componentRequireContext) - Create the directory
app/javascript/components. That's where your Preact components will reside. - Create your first Preact component - create the file
app/javascript/components/Button.jsand add the following lines:import { h, Component } from "preact" class Button extends Component { render (props, state) { return ( <button className="button" type={props.type}>{props.label}</button> ); } } export default Button - Ensure the javascript Pack is linked in Rails; the tag
<%= javascript_pack_tag 'application' %>is included inapp/views/layouts/application.html.erb - Render your Preact component in a view
<%= preact_component('Button', { type: 'submit', label: 'Get started!'}) %>