emi
emi

Reputation: 2950

Expose model data in component

Learning ReactJS. I created 2 records that I want to display in the components but not sure how to do it. I have:

toy_conroller.rb

class ToyController < ApplicationController
  def index
    @users = User.all
    render component: 'usersList', props: { users: @users }
  end
end

and a component that looks like:

userList.js.jsx

var usersList = React.createClass({
    propTypes: {
    name: React.PropTypes.string,
    age: React.PropTypes.number,
    country: React.PropTypes.string,
  },

    render: function() {
        return (
            <div>
            <h3>User List :D</h3>
            <table style={{border: 1}}>
                <thead>
                <tr>
                    <th>Name</th>
                    <th>Age</th>
                    <th>Country</th>
                </tr>
                </thead>
                <tbody>
                <tr>
                    <td>{this.props.name}</td>
                    <td>{this.props.age}</td>
                    <td>{this.props.country}</td>
                </tr>
                </tbody>
            </table> 
            </div>
            );
    }
});

How do I get the model data to show on my page? I see JS objects of my data in the console but not sure how to get them to show in the table.

enter image description here

Upvotes: 1

Views: 180

Answers (1)

Oleksandr T.
Oleksandr T.

Reputation: 77482

this.props.users is array of objects, you need loop over all items and get data from each of them

var UsersList = React.createClass({
  propTypes: {
    users: React.PropTypes.array
  },

  render: function() {
    var users = this.props.users.map(function (user) {
      return <tr key={ user.id }>
        <td>{ user.name }</td>
        <td>{ user.age }</td>
        <td>{ user.country }</td>
      </tr>;
    }, this);

    return <div>
      <h3>User List :D</h3>
      <table style={{border: 1}}>
        <thead>
          <tr>
            <th>Name</th>
            <th>Age</th>
            <th>Country</th>
          </tr>
        </thead>
        <tbody>
          { users }
        </tbody>
      </table> 
    </div>
  }
});

var users = [
  { id: 1, name: 'name', age: 'age', country: 'country' },
  { id: 2, name: 'name-1', age: 'age-1', country: 'country-1' },
]

ReactDOM.render(
  <UsersList users={ users } />,
  document.getElementById('container')
);
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react-dom.min.js"></script>
<div id="container"></div>

Upvotes: 1

Related Questions