Skip to main content

Render a Rails resource with a React Component

Javascript • Asked by Simon Cooper

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}

end

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) {
    super(props);
    this.state = {
      error: null,
      isLoaded: false,
      roasts: []
    };
  }

  componentDidMount() {
    fetch("roasts.json")
      //.then(res => res.json())
      .then(
        (result) => {
          this.setState({
            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) => {
          this.setState({
            isLoaded: true,
            error
          });
        }
      )
  }

  render() {
   let roasts = []
   this.props.roasts.map((roast) => {
      roasts.push(
        <tr key={roast.id}>
          <td>{roast.name}</td>
        </tr>
      )
    });
    return (
      <div>
        <h1>Roasts</h1>
        <div id="roasts">
          <table>
            <thead>
              <tr>
                <th>Name</th>
              </tr>
            </thead>
            <tbody>
              {roasts}
            </tbody>
          </table>
        </div>
      </div>
    );
  }
};



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.


Login or Create An Account to join the conversation.

Subscribe to the newsletter

Join 24,647+ developers who get early access to new screencasts, articles, guides, updates, and more.

    By clicking this button, you agree to the GoRails Terms of Service and Privacy Policy.

    More of a social being? We're also on Twitter and YouTube.