Ask A Question


You’re not receiving notifications from this thread.

Render a Rails resource with a React Component

Simon Cooper asked in Javascript

I'm going round in circles trying to work out, what I think must be a fairly common scenario, of tyring to render a rails resource through a React front end component.

I'm seem to have got as far as understanding I need to be able to pass down my resources as a props from my controller. I have the code below attempting to do that.

class RoastsController < ApplicationController
def index
@roasts = Roast.all
render component: 'RoastsJson', props: {roasts: @roasts}


I then understand I need a React component that can receive this props, and they render it in my view.

I have the follow code attempting to do that:

import React from 'react'
import ReactDom from 'react-dom'

class RoastsJson extends React.Component {

  constructor(props) {
    this.state = {
      error: null,
      isLoaded: false,
      roasts: []

  componentDidMount() {
      //.then(res => res.json())
        (result) => {
            isLoaded: true,
            items: result.roasts
        // Note: it's important to handle errors here
        // instead of a catch() block so that we don't swallow
        // exceptions from actual bugs in components.
        (error) => {
            isLoaded: true,

  render() {
   let roasts = [] => {
        <tr key={}>
    return (
        <div id="roasts">

export default RoastsJson

However, I'm just not getting this to work out. Am I fundamentally missing something? I'm under this impression that this scenario is a fairly common and typical use case but I'm struggeling to find any articles that succinctly explain how to go about it.


Hey there @Simon. In my case i had exactly the same issue and i fixed it with this:
all things are correct. try to change the code in controller just like this:

def index
roasts = Roast.all
respond_to do |format|
format.json { render json: roasts}

Join the discussion
Create an account Log in

Want to stay up-to-date with Ruby on Rails?

Join 83,453+ developers who get early access to new tutorials, screencasts, articles, and more.

    We care about the protection of your data. Read our Privacy Policy.