简体   繁体   中英

Creating react components from array data

I am creating a fairly simple stats page for a dashboard in my rails application. I am using react-rails to create react components in my app and have one for a stat card. 在此处输入图片说明

For these cards I have created a very simple react component

import React from "react";
import PropTypes from "prop-types";
class StatCard extends React.Component {
  render() {
    const { title, data } = this.props;
    return (
      <React.Fragment>
        <div className="card">
          <div className="card-body">
            <div className="row align-items-center">
              <div className="col">
                <h6 className="card-title text-uppercase text-muted mb-2">
                  {title}
                </h6>

                <span className="h2 mb-0">{data}</span>
              </div>
              <div className="col-auto">
                <span className="h2 fe fe-briefcase text-muted mb-0" />
              </div>
            </div>
          </div>
        </div>
      </React.Fragment>
    );
  }
}

StatCard.propTypes = {
  title: PropTypes.string,
  data: PropTypes.integer
};
export default StatCard;

In my html page right now I have 4 different components listed by calling this 4 different types with different data and a different title.

<%= react_component("StatCard", {title: 'Total users', data: @users.count }) %>

Would the best practice be to list an array of objects with this data listed and iterate over that and generate those components that way? If so, would this be data be best in the model or the controller?

The data structure might look something like this.

data = [
  { title: 'Total users', data: @users.count },
  { title: 'Total questions', data: @questions.count }
]

It is a good practice to have array of objects and iterate through that to return multiple similar components. you are using instance of user to get the count so it would be fine if you have them in controller

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM