This example is based on the LitElement tutorial, but based on Ruby2JS instead and hosted by Ruby on Rails. See the lit filter for more details.

Create a Project

Start a new project:

rails new ruby2js-litelement
cd ruby2js-litelement

Add the following line to your Gemfile:

gem 'ruby2js', require: 'ruby2js/rails'

Run the following commands:

./bin/bundle install
./bin/rails ruby2js:install:lit-webpacker

Write some HTML and a matching Custom Element

Generate a Rails controller:

./bin/rails generate controller Demo run

Create app/javascript/elements/my_element_element.js.rb with the following contents:

class MyElement < LitElement
   def self.styles
      p {
        font-family: Roboto;
        font-size: 16px;
        font-weight: 500;
      .red {
        color: red;
      .blue {
        color: blue;

  def initialize
    @message = 'Hello world! From my-element'
    @myArray = %w(an array of test data)
    @myBool = true

  def render
      <p class="#{@myBool ? 'red' : 'blue'}">styled paragraph</p>
      <ul>#{ {|item| "<li>#{item}</li>"}}</ul>
      #{@myBool ?
        "<p>Render some HTML if myBool is true</p>" :
        "<p>Render some other HTML if myBool is false</p>"}
      <button @click="#{clickHandler}">Click</button>

  def clickHandler(event)
    @myBool = !@myBool

customElements.define('my-element', MyElement)

Add the following to app/views/demo/run.html.erb:


Try it out!

Start your server:

./bin/rails server

Visit http://localhost:3000/demo/run. What you should see:

Next: React