Sunday, March 21, 2021

Add a React component to a Rails application

Why not sprinkle your Rails application with React components?

Prerequisites

  • Upgrade to Rails 6.x.x
  • Be using Webpacker in your application
  • Turbolinks

Install React &c.

In your project directory:

bin/rails webpacker:install:react

This will install react react-dom and some Babel packages with yarn. The Babel config and webpacker yml files are updated. (A sample hello world is also created under javascript/packs - should delete this upon studying)

Create a new pack for your component

Under

javascript/packs
name a file after the component you are using e.g chonky.js

The basic demo for Chonky looks like this in the new pack file:

// chonky.js

import * as React from 'react'
import { render } from 'react-dom'
import { setChonkyDefaults } from 'chonky'
import { ChonkyIconFA } from 'chonky-icon-fontawesome'
import { FullFileBrowser } from 'chonky'

setChonkyDefaults({ iconComponent: ChonkyIconFA })

document.addEventListener("turbolinks:load", (e) => {
  const el = document.getElementById("chonky-browser")
  if (el) {
    const files = [
          { id: 'lht', name: 'Projects', isDir: true },
          {
              id: 'mcd',
              name: 'chonky-sphere-v2.png',
              thumbnailUrl: 'https://chonky.io/chonky-sphere-v2.png',
          },
      ]
    const folderChain = [{ id: 'xcv', name: 'Demo', isDir: true }]
    render(<FullFileBrowser files={files} folderChain={folderChain} />, el)
  }
})
 

Add pack tag to application head

Within the head tags of

application.html.erb
add
<%= javascript_pack_tag 'chonky', 'data-turbolinks-track': 'reload' %>

Add element to HTML page passed to render function

<div id="chonky-browser"></div>



Monday, March 01, 2021

More social buttons

<ul style="padding:0">
  <li>
    <button onclick="window.open('https://twitter.com/intent/tweet?url=' + encodeURIComponent(document.URL) + '&text=' + encodeURIComponent(document.title) + '&via=YOUR_HANDLE', '_blank', 'width=550,height=420')" style="border:0;background:none;padding:0;width:45px;text-align:center;cursor: pointer;"><img src="https://cdn.cms-twdigitalassets.com/content/dam/developer-twitter/images/Twitter_logo_blue_48.png" alt="Twitter" height="48"/></button>
  </li>
  <li>
    <button onclick="window.open('https://www.minds.com/newsfeed/subscribed?intentUrl=' + encodeURIComponent(document.URL), '_blank', 'width=550,height=420')" style="border:0;background:none;padding:0;width:45px;text-align:center;cursor: pointer;"><img src="https://cdn-assets.minds.com/front/dist/en/assets/logos/bulb.svg" alt="Minds" height="48"/></button>
  </li>
</ul>