Crud for Users

Now we have our ReactToRails library in place, adding the Crud for users should be easy.

Here’s the store.

import Store from 'react-to-rails/store'
export const store = new Store('user')

Here’s the User view component.

export function User({user}) {
  return <div className='user'>
    <h2 className='name'>{user.name}</h2>
    <div className='email'>{user.email}</div>
  </div>
}

export default connectView(User, store)

And here’s the list:

export function List({users}) {
  return <ul className='users-list'>
    {
      users.map(user => <li key={user.id}>
        <User user={user}/>
      </li>)
    }
  </ul>
}

export default connectList(List, store)

There’s a bit of boilerplate-like overlap between the views and it’s tempting to try to abstract that away into the library but I actually like what Rails does with scaffolded views where it generates something simple that you can later edit. Maybe I’ll do that. Maybe I’ll do both.

I still need to build the Editor for users but that can wait until I get a bit further along with my understanding of forms in React. I think I want to work on a proper navigation scheme for the app first. It’s all a bit of a mess at the moment. But first we’ll have to learn about how to handle routes in React.

We’ll do that next week.

No more boilerplate!

The next story wants us to let authors edit their own posts but we don’t have an association between posts and users yet.

  • An author can edit a blog post.

We don’t have a way to create users either, except in the Rails console.

Normally, we’d scaffold a UI in Rails, but I want to do this in React to see how the Store that we created for posts generalises to other models and associations.

I’ll start by adding some missing details to the user model.

# rails g migration AddNameToUser name:string
class AddNameToUser < ActiveRecord::Migration[6.1]
  def change
    add_column :users, :name, :string
    add_column :users, :role, :integer
    add_index :users, :name, unique: true
  end
end

# User.rb
class User < ApplicationRecord
  authenticates_with_sorcery!
  enum role: [:guest, :author, :admin]

  validates :name,
            presence: true,
            uniqueness: true,
            length: { minimum: 2, maximum: 20},
            format: /\A[a-z_][\sa-z0-9_.-]+\z/i

  validates :email,
            presence: true,
            uniqueness: true,
            format: /\A[^@]+@[^@]+\.[^@]+\z/i
end

Now I’ll add a UsersController to return some JSON to the client. The tests are on GitHub.

# routes.rb
Rails.application.routes.draw do
  root to: 'posts#index'
  resources :posts
  resources :sessions
  resources :users

  get :sign_in,  to: 'sessions#new', as: :sign_in
end
class UsersController < ApplicationController
  skip_before_action :require_login, only: :show
  before_action :require_admin, except: :show
  before_action :set_user, except: :index

  helper_method :current_user, :admin?

  def index
    @users = User.by_name
  end

  def show
  end

  protected
  def set_user
    @user = User.find params[:id]
  end

  def admin?
    current_user&.admin?
  end

  def require_admin
    require_login
    raise Errors::AccessError unless admin?
  end
end
# app/lib/errors/access_error.rb
class Errors::AccessError < StandardError
-# views/users/index.json.jbuilder
json.users do
  json.partial! 'users/user', collection: @users, as: :user
end
-# views/users/show.json.jbuilder
json.partial! 'users/user', user: @user
-# views/users/_user.json.jbuilder
if admin?
  json.extract! user, :id, :name, :email, :role, :created_at, :updated_at
else
  json.extract! user, :id, :name
end

Now, after a bit of tidying, we have an AccessControl concern…

# app/controllerrs/concerns/access_control.rb
module AccessControl
  extend ActiveSupport::Concern

  included do
    before_action :require_login
    helper_method :current_user, :admin?
  end

  protected
  def admin?
    current_user&.admin?
  end

  def require_admin
    require_login
    raise Errors::AccessError unless admin?
  end
end


…that gets loaded by the ApplicationController and the UsersController simplifies to this:

class UsersController < ApplicationController
  skip_before_action :require_login, only: :show
  before_action :require_admin, except: :show
  before_action :set_user, except: :index

  layout 'react'
  
  def index
    @users = User.by_name
  end

  def show
  end

  protected
  def set_user
    @user = User.find params[:id]
  end
end

I also extracted a layout file for the react container so I don’t have to repeat it for every view that needs it.

<% content_for :body do %>
  <div id='react' data-user-id='<%= current_user&.id%>' />
<% end %>

<%= render template: 'layouts/application' %>

And now for the bit that I am most interested in. I want to make it as easy to create a React app — for the CRUD actions at least — as it is to do with Rails views.

Let’s look at the Store that we created for posts.

export class Store {
  constructor() {
    this.all = []
    this.by_id = {}
    this.subscribers = []
  }

  async list() {
    const {posts} = await list()
    this.addAndNotify(posts)
    return posts
  }

  async find(id) {
    let post = this.by_id[id]
    if(! post) {
      post = await fetch(id)
      this.addAndNotify(post)
    }
    return post
  }

  async create(post) {
    post = await create(post)
    // todo don't add it to the store unless it is valid
    this.addAndNotify(post)
    return post
  }

  addAndNotify(post_or_posts) {
    if(Array.isArray(post_or_posts))
      post_or_posts.forEach(post => this.add(post))
    else
      this.add(post_or_posts)

    this.all = Object.values(this.by_id).sort(by_created_at)
    this.notify()
  }

  add(post) {
    this.by_id[post.id] = post
  }

  // extract this to a class
  subscribe(fn) {
    this.subscribers.push(fn)
  }

  unsubscribe(fn) {
    this.subscribers = this.subscribers.filter(subscriber => subscriber !== fn)
  }

  notify() {
    //  do a dispatch thing here with a queue
    this.subscribers.forEach(fn => fn())
  }
}

export const store = new Store()

There’s nothing about that that is specific to posts. It should work for any model so let’s extract the beginning of a library for binding the React UI to the Rails API with minimal coding.

I moved the Store to the new directory that will be the start of our library and parameterised the constructor to take a type.

// ReactToRails/store.js
export default class Store {
  constructor(type) {
    this.type = type
    this.plural = pluralize(type)
    this.all = []
    this.by_id = {}
    this.subscribers = []
  }
  // ...

I moved everything into this directory that is not part of the Blogging domain: api.js; sorting.js; server.js. Everything.

I parameterised the api calls to take a type. It uses the simple rule that URLs take the form /plural-of-type.json which covers the majority of URLs. When we get one that doesn’t follow this rule, we’ll do something more sophisticated.

export function fetch(type, id) {
  return server.get(pathToShow(type, id))
}

export function list(type) {
  return server.get(pathToIndex(type))
}

export function create(type, record) {
  return server.post(pathToIndex(type), {[type]: record})
}

function pathToShow(type, id) {
  return `/${pluralize(type)}/${id}.json`
}

function pathToIndex(type) {
  return `/${pluralize(type)}.json`
}

export function pluralize(type) {
  return `${type}s`
}

Let’s look at those ConnectedXXX components next.

// posts/List.jsx
export default class ConnectedList extends React.Component {
  constructor(props) {
    super(props)

    this.store = this.props.store || store
    this.state = {
      posts: null
    }

    this.storeDidUpdate = this.storeDidUpdate.bind(this)
  }

  render() {
    const {posts} = this.state
    if(posts === null) return 'Loading…'
    return <List posts={posts} />
  }

  async componentDidMount() {
    const posts = await this.store.list()
    this.setState({posts})
    this.store.subscribe(this.storeDidUpdate)
  }

  componentWillUnmount() {
    this.store.unsubscribe(this.storeDidUpdate)
  }

  storeDidUpdate() {
    const posts = this.store.all
    this.setState({posts})
  }
}

That’s 98% boilerplate and we can extract that away to the library too. Let’s try a higher-order component (HOC) the way that Redux does for connected components.

According to the React site,

a higher-order component is a function that takes a component and returns a new component.

We are going to use it for two things:

  1. To parameterize the ConnectedList.
  2. To connect the list to the store.

Here it is:

// ReactToRails/ConnectedList.jsx

export function connectList(WrappedList, store) {
  return class extends React.Component {
    constructor(props) {
      super(props)

      this.state = {
        records: null
      }

      this.storeDidUpdate = this.storeDidUpdate.bind(this)
    }

    render() {
      const {records} = this.state
      if (records === null) return 'Loading…'

      const props = {
        [store.plural]: records
      }
      return <WrappedList {...props} />
    }

    async componentDidMount() {
      const records = await store.list()
      this.setState({records})
      store.subscribe(this.storeDidUpdate)
    }

    componentWillUnmount() {
      store.unsubscribe(this.storeDidUpdate)
    }

    storeDidUpdate() {
      const records = store.all
      this.setState({records})
    }
  }
}

It’s functionally equivalent to the ConnectedList we had before, but this one lets us pass in a store object and a List component. and it doesn’t care about the types.

Here’s what it does:

  1. Fetch a list of records from the store.
  2. Subscribe to updates from the store.
  3. Updated the WrappedList when the records are added to the store.

We can call from list.jsx.

// posts/list.jsx
export default connectList(List, store)

We can do the same de-boilerplating for the ConnectedPost component.

// ReactToRails/ConnectedView.jsx
export function connectView(WrappedView, store) {
  return class extends React.Component {
    constructor(props) {
      super(props)

      this.store = this.props.store || store
      this.state = {
        record: {}
      }
    }

    render() {
      const {record} = this.state
      const props = {
        [this.store.type]: record
      }
      return <WrappedView {...props} />
    }

    async componentDidMount() {
      const record = await this.store.find(this.props.id)
      this.setState({record})
    }
  }
}
export default connectView(Post, store)

All the boilerplate is gone from our App now and, with any luck, it should be easy to add the crud pages for users.

Deploy a React/Rails app to Heroku

Now that we are all secure, we can deploy our new blogging platform to the interwebs. Heroku makes it super easy and gives you clear instructions at every step. I’ll just summarize the highlights here.

Start by creating a Heroku account and then go to your Heroku dashboard at https://dashboard.heroku.com/apps and click the NEW button.

Heroku has a free tier that restricts you to a certain number of hours of availability and rows in the database. Even the next level up (Hobby Tier) only costs $7 per month.

Once the app is created, Heroku gives you custom instructions to deploy your app.

For me it was:

heroku login
heroku git:remote -a react-to-blogging
git push heroku master

Heroku does not run the database migrations automatically so I’ll do that now.

heroku run rails db:migrate

I’ll need to create a user and sign in before I can post. I can get to the rails console with…

heroku run rails console

…and I can create a user record with…

User.create! email: 'sally@example.com', password: 'XXXXXXXX'

Now I can sign and post. That’s it. I’m blogging on Heroku.

You can visit the blog here: https://react-to-blogging.herokuapp.com/

One last thing: While I was deploying, I noticed a warning message saying that a Procfile is recommended. I haven’t seen any downsides of not having one but it gives you a place to run migrations automatically so I’ll add one now.

I copied this from somewhere or other.

web: bundle exec puma -C config/puma.rb
release: rake db:migrate

Back to writing code! What’s next, I wonder.

Managing State in a React Application

Just to recap where we left off.

We can:

  1. Fetch a post from the server and display it.
  2. Create a new post and send it to the server.
  3. Fetch a list of posts from the server and display them.

It’s all tested and checked in to GitHub here and all the tests are running in CircleCI here.

We just discovered a problem though. Although you can create a new post, it doesn’t show up in the list of posts unless you refresh the page.

This is the point where I would usually reach for Redux but I have an idea for a state management library that is more Rails-friendly and requires less boilerplate code. Will it work? Who knows! Maybe I’ll just end up rebuilding Redux.

I am going to try though.

I want something that will be familiar to Rails developers and use many of the same API conventions. I’ll try to follow the Rails ideal of convention-over-configuration and, where there is configuration already on the server, I’ll try to use that. Wish me luck!

Let’s start with a Store that can be accessed by all the connected components.

// posts/Store.test.jsx
describe('The post store', () => {
  test('is initially empty', () => {
    const store = new Store()
    expect(store.all).toEqual([])
  })
})
// posts/Store.js
export class Store {
  constructor() {
    this.all = []
  }
}

// There's one store accessible to whoever needs it.
export const store = new Store() 

If someone calls list(), the store should go fetch posts from the server.

describe('The post store', () => {
let store
server.send = jest.fn()
const post = {
id: 1,
title: 'The Title',
body: 'The body.',
}

beforeEach( () => {
store = new Store()
})

test('is initially empty', () => {
expect(store.all).toEqual([])
})

test('fetches the list of posts from the server', async () => {
server.send.mockReturnValue({posts: [post]})

const posts = await store.list()
expect(posts.length).toEqual(1)
expect(posts[0].title).toEqual('The Title')
expect(store.all).toEqual(posts)

expect(server.send).toBeCalledWith('/posts.json')
})
})
export class Store {
  constructor() {
    this.all = []
  }

  async list() {
    const {posts} = await list()
    this.all = posts
    return posts
  }
}

Now we’ll edit ConnectedList to get its posts from the store instead of directly from the server. No need to change the tests; they should still just work.

export default class ConnectedList extends React.Component {
  async componentDidMount() {
    const posts = await store.list()
    this.setState({posts})
  }
}

Our next trick is to notify subscribers when a post is added to the store.

  test('notify subscribers when a post is added to the store', async () => {
    const subscriber = jest.fn()
    store.subscribe(subscriber)

    store.addAndNotify(post)

    expect(subscriber).toBeCalled()
    expect(store.all[0]).toEqual(post)
  })
export class Store {
  constructor() {
    this.all = []
    this.subscribers = []
  }

  async list() {
    const {posts} = await list()
    this.all = posts
    return posts
  }

  addAndNotify(post) {
    this.all = [...this.all, post]
    this.notify()
  }

  // extract this to a class
  subscribe(fn) {
    this.subscribers.push(fn)
  }

  unsubscribe(fn) {
    this.subscribers = this.subscribers.filter(subscriber => subscriber !== fn)
  }

  notify() {
    this.subscribers.forEach(fn => fn())
  }
}

And now we can hook the ConnectedList component up as a subscriber to the store.

// posts/List.test.jsx
  test('updates the list when a post is added to the store', async () => {
    server.send.mockReturnValue({posts: []})

    const component = await displayConnected(<ConnectedList store={store} />)
    assert_select(component, '.post', 0)

    store.addAndNotify(post)
    component.update()
    assert_select(component, '.post', 1)
  })

I did a little tidying here to allow us to pass in the store as a property to make tests easier to isolate from one another.

And, finally, here’s the ConnectedList, now subscribing to changes in the store.

  async componentDidMount() {
    const posts = await this.store.list()
    this.setState({posts})
    this.store.subscribe(this.storeDidUpdate)
  }

  componentWillUnmount() {
    this.store.unsubscribe(this.storeDidUpdate)
  }

  storeDidUpdate() {
    const posts = this.store.all
    this.setState({posts})
  }

I’m going to stop showing all my tests from here on since you probably get the idea already and it’s TDDious to show every little change. I’ll share the test if there is something new and interesting but, otherwise, I’ll stick to the code. I am still TDDing behind the scenes of course and, if you are interested, you can see all the tests in the GitHub repository here.

There are a couple of loose ends though. I should make all the components use the store instead of doing their own thing.

I’ll start with ConnectedPost. I’ll make the store maintain a list of posts by id and return the local copy if it already has one.

// store.js
  async find(id) {
    let post = this.by_id[id]
    if(! post) {
      post = await fetch(id)
      this.addAndNotify(post)
    }
    return post
  }

  async list() {
    const {posts} = await list()
    this.addAndNotify(posts)
    return posts
  }


  addAndNotify(post_or_posts) {
    if(Array.isArray(post_or_posts))
      post_or_posts.forEach(post => this.add(post))
    else
      this.add(post_or_posts)
    
    this.all = Object.values(this.by_id)
    this.notify()
  }

  add(post) {
    this.by_id[post.id] = post
  }

Don’t forget we need to sort the posts by date.

  addAndNotify(post_or_posts) {
    // ...    
    this.all = Object.values(this.by_id).sort(by_created_at)
    // ...
  }


// sorting.js
export function by_created_at(a, b) {
  if(a.created_at === b.created_at) return 0
  if(a.created_at > b.created_at) return -1
  return 1
}

Now to add a create method to the store…

// posts/store.js
  async create(post) {
    post = await create(post)
    this.addAndNotify(post)
    return post
  }

…and finally, we can call it from the post Editor

async handleSubmit(event) {
event.preventDefault()

const {post} = this.state
await this.store.create(post)
}

…and our job here is done.

We’ll reflect on where we are tomorrow because, now, we’ve earned ourself a pint of IPA at The Broken Dock.

Testing asynchronous components

I had a couple of gaps in my tests (I wasn’t testing the ConnectedPost) and I ran into the issue again where the HTML was not updated after an asynchronous call to the server. I did a a little research to figure out why.

When you make a call with await in a function, like this:

  async componentDidMount() {
    const post = await fetch(this.props.id)
    this.setState({post})
  }

Javascript returns a promise which gets resolved later. The React framework takes care of that eventually but, when you render your component in a test, you need to make sure all the promises are resolved before you check the resulting HTML.

Jest gives us a function to make that happen and I am going to add a helper to my React helper file to make it easy to use.

// ReactHelper.jsx
export const resolveAllPromises = () => new Promise(setImmediate)

Whenever I test a component that makes asynchronous calls, I have to remember to call resolveAllPromises() and make the test function async, like this:

// posts/Post.test.jsx
  test('fetches a post from the server', async () => {
    server.send.mockReturnValue(post)

    const component = display(<ConnectedPost id={1}/>)
    await resolveAllPromises()
    component.update()

    assert_select(component, '.post .title', 'The title')
    expect(server.send).toBeCalledWith('/posts/1.json')
  })

But wait! Why should I have to remember do call that every time? I can add it to the helper like this:

// ReactHelper.jsx

export async function displayConnected(component) {
  const connected = mount(component)

  await resolveAllPromises()
  connected.update()

  return connected
}

And now the test becomes much simpler:

  test('fetches a post from the server', async () => {
    server.send.mockReturnValue(post)

    const component = await displayConnected(<ConnectedPost id={1}/>)

    assert_select(component, '.post .title', 'The title')
    expect(server.send).toBeCalledWith('/posts/1.json')
  })

I’m glad that’s straightened out. Back to the storyline.

What do you want to see?

As of now, we can create a new post and we can show one hard-coded post. It’s almost time to add some structure and navigation to our app. Let’s show a list of posts first, though, and we can think about how we navigate between items later.

Let’s add a list component to show all the posts. We’ll fake it in the front end…

export function Main() {
  return <div id='main'>
    <Editor onSubmit={create} />
    <List />
  </div>
}
// /javascript/posts/List.jsx
export default class List extends React.Component {
  render() {
    return 'list of posts'
  }
}

… until we have the backend in place.

The posts.index action in PostsController will return the React application if you request HTML and a list of posts if you request JSON.

# PostsControllerTest.rb
  
test 'the index page just returns the react application' do
  get posts_url
  assert_select '#react'
end

test 'fetch a list of posts as json' do
  get posts_url(format: :json)
  assert_response :success
  json = JSON.parse response.body, symbolize_names: true

  assert 1, json[:posts].count
  assert 'The title', json[:posts][0][:title]
end
# PostsController.rb

def index
  @posts = Post.all.order(created_at: :desc)
end

# index.json.jbuilder
json.posts do
  json.array! @posts do |post|
    json.extract! post, :id, :title, :body, :created_at, :updated_at
  end
end

And, if I open http://blogging.local:3000/posts.json in the browser, I see my posts. Now to fetch them from the client.

I’ll add an API methods to fetch the list of posts…

// posts/api.js

export function list() {
  return server.get(`/posts.json`)
}

…and update the List component to call it and render the list.

export default class List extends React.Component {
  constructor(props) {
    super(props)
    this.state = {
      posts: null
    }
  }

  render() {
    const {posts} = this.state
    if(posts === null) return 'Loading…'

    return <ul className='posts-list'>
      {
        posts.map(post => <li key={post.id}>
          <Post post={post}/>
        </li>)
      }
    </ul>
  }

  async componentDidMount() {
    const response = await list()
    this.setState({posts: response.posts})
  }
}

That’s all straightforward, I think, except: note the key property in <li key={post.id}>.

React performs optimisations by keeping track of changes to the React component tree and only re-rendering components that have changed since the last render. When you render an array of components you should provide a unique key to each component to help React figure out what has changed.

If I run all the Javascript tests now, I see a failure in the top-level Application.test.jsx because it is still expecting a single Post component rather than a list.

Let’s fix that.

// Application.test.jsx

describe('The application', () => {
  server.send = jest.fn()

  const post = {
    id: 1,
    title: 'React on Rails',
    body: 'I can use React with Rails.',
  }

  const posts = [post]

  beforeEach( () => {
    // Return a list of posts instead of a single post
    server.send.mockReturnValue({posts})  
  })

  test('shows a list of blog posts', async () => {
    const component = await display(<Application />)
    component.update()

    assert_select(component, '.site-name',   'Blogging')
    assert_select(component, '.post .title', 'React on Rails')
    assert_select(component, '.post .body',  'I can use React with Rails.')

    expect(server.send).toBeCalledWith('/posts.json')
  })
})

I’m not sure why, but I had to add component.update() to get the list component to render the correct HTML (I think this might be a bug in Enzyme).

I like to think of the top-level Application.test as a kind of smoke test that tests the whole application from end to end, albeit in a rather shallow fashion. It won’t tell us anything profound about the application’s behaviour but it might flag some future regression that would be missed by lower-level unit tests.

As I did with the Post.test, I’ll duplicate this test as a unit test so I can test the List component more thoroughly. But first I am going to split the component into a List that knows how to render a list of posts and a ConnectedList that knows how to fetch a list of posts from the server.

This seems like a lot of faff when I am typing it into WordPress but it’s literally 10 seconds of copy-paste in the IDE and my future self will thank me when I need to write more complex tests and I can do so without loading the whole framework.

Here’s the code.

// posts/List.jsx

export function List({posts}) {
  return <ul className='posts-list'>
    {
      posts.map(post => <li key={post.id}>
        <Post post={post}/>
      </li>)
    }
  </ul>
}

export default class ConnectedList extends React.Component {
  constructor(props) {
    super(props)
    this.state = {
      posts: null
    }
  }

  render() {
    const {posts} = this.state
    if(posts === null) return 'Loading…'
    return <List posts={posts} />
  }

  async componentDidMount() {
    const response = await list()
    this.setState({posts: response.posts})
  }
}

And here are the tests: one for the List and one for the ConnectedList.

// posts/List.test.jsx
describe('The post list', () => {
  server.send = jest.fn()

  const post = {
    id: 1,
    title: 'React on Rails',
    body: 'I can use React with Rails.',
  }
  const posts = [post]

  test('shows a list of blog posts', () => {
    const component = display(<List posts={posts}/>)

    assert_select(component, '.posts-list .post', 1)
    assert_select(component, '.post .title', 'React on Rails')
    assert_select(component, '.post .body',  'I can use React with Rails.')
  })

  test('fetches the list of blog posts from the server', async () => {
    server.send.mockReturnValue({posts})

    const component = await display(<ConnectedList />)
    component.update()

    assert_select(component, '.posts-list .post', 1)
    expect(server.send).toBeCalledWith('/posts.json')
  })
})

A quick test in the browser shows that I can show a list of posts from the server and I can create a new one except… Ooops!… the new one doesn’t get added to the list unless I refresh the page.

This is the kind of problem that Redux will solve for us but I have a different approach in mind. We’ll give it a try in the next episode.

Forms are not Simple

I miss simple_form already. Forms in React are such a pain and I hope to recreate the simple_form experience. We’ll take it a step at a time.

We’ll start by shoving a form onto the main page. We’ll tidy it up later.

// app/javascript/application/Application.jsx

export function Application(_props) {
  return <div id='application'>
    <h1 className='site-name'>Blogging</h1>
    <form>
      <input type='text' name='title' />
      <textarea name='body' />
      <input type='submit' />
    </form>
    <Post id={1} />
  </div>
}

Oh, dear. That’s ugly.

Come to think of it, the whole app is pretty ugly. Let’s tidy.

That’s better. It won’t win any prizes but it’s good enough for now.

I won’t show you the CSS (and you probably won’t like it anyway) but it’s all checked in if you want to peek.

I added a couple of divs and some CSS classes to the top-level elements too. I’ll show you in a bit, but first I am gonna move that form to its own component. I’m not TDDing this bit because I’m kind of stumbling around to find something that works. I’ll test it later.

Here’s the code after tidying the page structure and extracting an Editor.

export function Application() {
  return <div id='application'>
    <div id='header' className='header'>
      <h1 className='site-name'>Blogging</h1>
    </div>

    <div id='main'>
      <Editor />
      <Post />
    </div>
  </div>
}

Let’s extract a Header and Main section too before we get back to the form.

The Application now looks like this.

export function Application() {
  return <div id='application'>
    <Header />
    <Main />
  </div>
}

The header looks like this.

// javascript/application/Header.jsx
export function Header() {
  return <div id='header' className='header'>
      <h1 className='site-name'>Blogging</h1>
    </div>
}

The Main component looks like this.

export function Main() {
  return <div id='main'>
      <Editor />
      <Post id={1} />
    </div>
}

And the Editor looks like this.

export function Editor() {
  return <form>
      <input type='text' name='title'  className='title'/>
      <textarea name='body' className='body' />
      <div className='actions'>
        <input type='submit' className='button'/>
      </div>
    </form>
}

I wrote a test for the editor. It doesn’t do much yet.

// test/javascript/posts/Editor.test.jsx
describe('The post editor', () => {
  test('displays a form', () => {
    const component = display(<Editor />)
    assert_select(component, '.title')
    assert_select(component, '.body')
  })
}

Controlled Components

React has this concept of controlled components versus uncontrolled components. This concept comes to the fore when you use form elements.

Long story short, when we are writing plain HTML forms, we rely on the form elements to manage their own state that they magically send to the server when you hit SUBMIT. In React, we usually manage the state ourselves and do our own submitting.

A component is said to be controlled if its state changes are managed in a containing component. The basic idea is that you store the values from your form elements in React state, then pass them back in as properties when you render the form.

You can read more about controlled components here: https://reactjs.org/docs/forms.html

Here. Let me just show you.

export default class Editor extends React.Component {
  constructor(props) {
    super(props)
    this.state = {
      post: {}
    }
    this.handleChange = this.handleChange.bind(this)
    this.handleSubmit = this.handleSubmit.bind(this)
  }

  render() {
    const {post} = this.state

    return <form onChange={this.handleChange}
                 onSubmit={this.handleSubmit}>
      <input type='text' name='title' className='title' defaultValue={post.title} />
      <textarea name='body' className='body' defaultValue={post.body} />
      <div className='actions'>
        <input type='submit' className='button' />
      </div>
    </form>
  }

  handleChange(event) {
    const {name, value} = event.target
    const post = {
      ...this.state.post,
      [name]: value
    }
    this.setState({post})
  }

  handleSubmit(event) {
    event.preventDefault()

    const {post} = this.state
    const {onSubmit} = this.props
    onSubmit && onSubmit(post)
  }
}

I’ve converted our Editor function to a class so that we can manage its state. I’ve set up some state for the form elements and I’ve added an event handler for the onChange event.

When the user changes the value of the title element or the body element, the onChange event bubbles up to the form element where we handle it and store the value with this.setState(post).

The {…} in the handler is a spread operator. I’m using it to make a copy of post and overwriting one property. React really doesn’t like it when you mutate objects directly and the spread operator provides an easy way to make a copy without changing the original object.

When you submit the form, Editor calls an onSubmit function that was passed in as a property. It calls event.default() first to prevent the page refresh and then writes the current state of the post to the console.

That’s all quite straightforward, I think, except: let me draw your attention to the bind code in the constructor.

this.handleChange = this.handleChange.bind(this)

In Javascript, the value of this is elusive and fleeting and often not what you think it is. In this situation, when our event handler tries to handle the onChange event, the value of this will be null and weird errors result unless you call bind().

Mozilla has more details about binding here.

Now we have something we can test.

// test/javascript/posts/Editor.test.jsx

  test('updates the post details', () => {
    const submit = jest.fn()
    const component = display(<Editor onSubmit={submit} />)

    const title = component.find('.title')
    const body = component.find('.body')
    const form = component.find('form')

    title.simulate('change', {target: {name: 'title', value: 'The title'}})
    body.simulate('change',  {target: {name: 'body', value: 'The body'}})
    form.simulate('submit')

    const expected = {
      title: 'The title',
      body: 'The body',
    }
    expect(submit).toBeCalledWith(expected)
  })

I’ve mocked the onSubmit function and I check that, when I edit the fields and submit the form, the right thing comes out the other end.

In the next episode, we’ll send this new post to the server.

Testing with Jest and Enzyme

I find it hard to do test-first with UI components because I’m always in such a rush to see what the UI will look like. But test-last is better than no test, so let’s test now.

Jest is a unit testing library for Javascript and Enzyme provides an adapter that lets you interact with React components from your test code. We’ll install them using the Yarn package manager.

yarn add --dev jest
yarn add --dev enzyme
# Apparently enzyme-adapter-react-17 doesn't work. 
# yarn add --dev enzyme-adapter-react-17

# But this does.
yarn add --dev @wojtekmaj/enzyme-adapter-react-17

Let’s create a test for our Application component.

// test/javascript/application/Application.test.js

import React from 'react'
import {mount} from 'enzyme'
import {configure} from 'enzyme'
// import Adapter from 'enzyme-adapter-react-17'
import Adapter from '@wojtekmaj/enzyme-adapter-react-17';

configure({ adapter: new Adapter() })

import {Application} from 'application/Application'

describe('The application', () => {
  test('shows the first blog post', () => {
    const component = mount(<Application />)

    expect(component.find('.site-name').text()).toBe('Blogging')
    expect(component.find('.title').text()).toBe('React on Rails')
    expect(component.find('.body').text()).toBe('I can use React with Rails.')
  })
})

mount() will instantiate your component, call all the React lifecycle methods (we’ll cover this later), render it and make the component available for you to write assertions against.

A note about rendering components with Enzyme.

Enzyme has three different methods for rendering a React component:

  • shallow(<C />) renders C but not its child components.
  • mount(<C />) renders C and, recursively, all of its children.
  • render(<C />) renders just the component’s HTML.

It took me a long time to realize that these three methods do totally different things and each has a totally different API. This confused the hell out of me for weeks. Once I realized that, I decided to just stick with mount() unless I have a very good reason to just do a shallow rendering which, so far, is never.

A minor rant about behavioural-style test frameworks

Way back when the first JUnit extensions appeared that let you write tests in pseudo-English so your customer could read them, or maybe even write them, Ron Jeffries said that this was a dead end.

Pseudo-English would always have an uncanny valley feel about it; the tests would be hard to read and harder to write. If programmers write tests, better that they use normal programming conventions that programmers can understand.

I didn’t listen.

After struggling mightily with Fit, Fitnesse, Cucumber, RSpec and God Knows What Else, I decided that maybe Ron had a point and went back to plain JUnit-style assertions.

I don’t know about you, but I find this…

assert_equal 'Blogging', component.find('.site-name').text()

…much easier to read (and write!) than…

expect(component.find('.site-name').text()).toBe('Blogging')

Even better would be…

assert_select('.site-name', 'Blogging')

…and maybe I’ll do something about that one day.

In 20-something years, I’ve never had a customer who was interested in reading — never mind writing — these tests. Just write your best ruby/javascript/whatever and give the tests good names. It will be OK.

Running the tests

We have to tell Jest where to find the tests. Create jest.config.js in the root of your rails app.

// jest.config.js
module.exports = {
  moduleDirectories: [
    "node_modules",
    "app/javascript"
  ],

  rootDir: 'test/javascript',
  clearMocks: true,
  coverageDirectory: "test/results/coverage",
  testMatch: [
    "**/*.test.jsx",
  ],
}

We can run the test with

yarn jest

Continuous Integration

If you sign in to CircleCI via your GitHub account, you can have CircleCI run your tests for you.

Click Set Up Project then follow the instructions to add the CircleCI config file to your project. I won’t repeat them here. If you are lucky, it will work first time.

If you are unlucky like me, you’ll have to copy a working config.xml from somewhere else. You can copy mine if you like. I had to add minitest-ci to my Gemfile to get the test results to show up. I got there in the end.

If you want to be really fancy, you can add the little badge that CircleCI generates to your README.md file.

Here’s mine:

And here it is on GitHub:

https://github.com/klawrence/blogging

Time to write some more code.

In the next instalment, we’ll hook our React component up to use our Rails JSON api.

Introducing React Components

Let’s recap what we’ve done so far.

Let’s work on the React app that will turn our JSON into a beautiful blog post. I like to start with a completely hardcoded UI and work back incrementally from there until it connects with the JSON. We’ll start by deleting the Hello React app and replacing it with the real thing.

If you look under the app/javascript folder, you’ll see two packs.

We’ll delete hello_react.jsx and fix up the application pack to show our blog post. Webpacker gets its knickers in a twist when you delete a pack but stopping and starting webpack-dev-server will usually fix it.

I like to have a top-level Application component that acts as a container for everything else. I also like to group my components on the file system by domain rather than the more usual functional buckets.

Let’s create the Application component and initialize it. I’ll explain what it is doing afterwards.

// javascript/application/Application.jsx
import React from 'react'

export function Application(props) {
  return <div id='application'>
    <h1 className='site-name'>Blogging</h1>
    <h2 className='title'>React on Rails</h2>
    <div className='body'>I can use React with Rails.</div>
  </div>
}

A few things to note if you are new to React.

React has a syntax that looks a lot like HTML for describing views. But it’s not HTML, it’s JSX!

JSX is an extension to Javascript syntax that gets compiled into React components. It’s hard to love JSX and why anyone thought it was a good idea to write code with angle brackets in the 21st century, I have no idea. I thought I was done with remembering to close tags about ten years ago. Maybe I should learn Pug next.

The simplest React component is just a function that returns some JSX. That thing that looks a bit like a <div> tag with an id attribute… that will actually get compiled into code that creates a div component and sets the id property. React components are all about the properties.

You may remember that HTML has a class attribute. But class is a reserved word in Javascript so React uses className instead (React components use camelCase for property names). You’ll remember this after you get it wrong the first 27 times.

The usual trick for bootstrapping a React app is to look for an element in the DOM and then render your React component inside it.

# javascript/application/index.jsx

import React from 'react'
import ReactDOM from 'react-dom'
import {Application} from './Application'

document.addEventListener('DOMContentLoaded', () => {
  const react = document.querySelector('#react')
  ReactDOM.render(
      <Application />,
      react.appendChild(document.createElement('div'))
  )
})

Here’s that div element with id=’react’ on our index page. We don’t need to include the javascript_pack_tag because the application layout file already includes it.

# index.html.erb
<div id='react' />

The last thing is to point the application pack file at our index.jsx.

// javascript/packs/application.js
import 'application'

If you import a folder, Javascript looks for an index.js (or index.jsx) file and runs that. If you have been following along, your javascript folder should look like this:

If you refresh your browser page now, it should look a bit like this:

So that’s our top level Application component done. In the next episode we’ll tidy it up a little and add some tests.

A quick bonus tip before I go.

I like to add an entry to /etc/hosts for each local project. It saves you from resurrecting the ghost favicons from long-forgotten projects and stops your cookies from colliding if you are working on multiple projects at the same time.

# /etc/hosts
127.0.0.1       localhost blogging.local

Rails requires you to declare the host name as a security measure.

# config/environments/development.rb
Rails.application.configure do
  config.hosts << 'blogging.local'
  …

Don’t forget to restart the rails server if you change the environment files.

Now I can open the app in the browser with

open http://blogging.local:3000/posts/1.json

React on Rails

When I was first learning React I went through about 17 tutorials before I finally grokked what it was all about. Which is weird because React is quite simple really.

I’m gonna build the tutorial that I wished I’d had when I started learning it.

I’ll assume my reader knows Rails very well but knows just enough Javascript to add sprinkles. I won’t try to teach you React, but I’ll point you in the right direction to learn what you need to know.

Let’s do this.

But “Do what?” you may ask?

We are going to build a blogging platform. It’s going to be Rails on the back end and React on the front end. We’re going to test with Minitest, Jest and Enzyme as we go along. We’ll deploy it on Heroku. We’ll use CircleCI for continuous integration.

We are not going to use Redux. I have an idea for a more object-oriented state management system that leverages the rich metadata that Rails already has and, hopefully, avoids all the acres of boilerplate code that every other React tutorial seems to generate. I don’t have a design for this in mind. I’m hoping one will emerge as we go along.

Let’s start with a quick planning session. What do we want our blogging platform to do?

  • An author can publish a blog post.
  • A reader can read a blog post.
  • The home page shows a list of posts, most recent first.
  • An author can edit a blog post.
  • Readers can comment on a post.
  • Comments are held for moderation.
  • The author can approve comments.
  • Notify the author when there are comments.

At some point we’ll want to upload images and have multiple authors and fancy formatting and RSS feeds and other blogphernalia but that list is enough to get us started.

I’ll tackle the second story first because I like to get something working from end to end as quickly as possible and reading a post has fewer moving parts than creating one.

Join me here to get started.

Episodes

I’ll add links to all the episodes here for folks who want to skip ahead.

  1. Install Rails, Yarn, React & create a project on GitHub.
  2. Create a Post model in Rails and show the JSON.
  3. Introducing React components.
  4. Testing React with Jest & Enzyme. Setup CircleCI.
  5. Introduce class components and load a post from the server.
  6. Mock the API call to the server.
  7. Add a test helper to make testing React components easier.
  8. Create a new post in our PostsController.
  9. Use a controlled form to create a new post.
  10. Connect our new form to the back end to create a post.
  11. Fetch a list of posts from the server.
  12. Testing asynchronous components.
  13. Managing state in a React application.
  14. CHECKPOINT: Review the plan.
  15. Add a user model for registration and sign in.
  16. Deploy to Heroku.
  17. Extract our ReactToRails library to eliminate some boilerplate.
  18. Use the ReactToRails library to build the CRUD for users.