在React中构建一个在线零售仪表盘

In this tutorial, we’ll be focusing on creating a dashboard for an Online Retail Store. Online Retail Stores generate revenue across other e-commerce giants, apart from their own website. This dashboard focuses on showcasing a monthly performance of an online store across three e-commerce aggregators - Amazon, Ebay and Etsy. Further, we have used a combination of Charts, Maps, and KPI elements to showcase how different sources of revenue are performing, and from which geo locations are maximum orders are coming in from. Hope you have as much fun building this dashboard, as I did!

在本教程中,我们将专注于为在线零售商店创建仪表板。 除了自己的网站之外,在线零售商店还为其他电子商务巨头带来收入。 该仪表板专注于展示跨三个电子商务聚合器(Amazon,Ebay和Etsy)的在线商店的每月绩效。 此外,我们结合使用了“图表”,“地图”和“ KPI”元素来展示不同的收入来源是如何执行的,以及最大订单来自哪个地理位置。 希望您能像我一样乐于构建该仪表板!

Before we go ahead setting up, I wanted to show you a preview of the Online Retail Dashboard you’ll be able to create, once you’ve gone through this tutorial. Here’s a live link to dashboard in action.

在继续进行设置之前,我想向您展示完成本教程后可以创建的Online Retail Dashboard的预览。 这是操作中的仪表板的实时链接

搭建环境 ( Setting up the Environment )

Including Dependencies We’ll be using the following dependencies for this project. To create the dashboard, you’ll need to set-up these dependencies as explained below:

包括依赖项我们将在该项目中使用以下依赖项。 要创建仪表板,您需要按照以下说明设置这些依赖项:

  1. React, Bootstrap

    React,引导
  2. FusionCharts Core Package, its React Component and FusionMaps package

    FusionCharts核心软件包,其React组件和FusionMaps软件包

Including React We’ll be using Facebook’s React boilerplate today, which will set-up React along with all the utilities that we need. So, in your terminal, go ahead and enter:

包括React我们今天将使用Facebook的React样板,它将设置React以及我们需要的所有实用程序。 因此,在您的终端中,继续输入:

$ npx create-react-app ecommerce-dashboard

To know more about create-react-app, please refer to this link. Now, we will be adding a few more components that we will need for this tutorial, as explained below:

要了解有关create-react-app更多信息,请参阅此链接 。 现在,我们将添加本教程所需的其他一些组件,如下所述:

Including Bootstrap We will be using Bootstrap to create the layout and user-interface for our app. So, in the terminal go ahead and enter:

包括Bootstrap我们将使用Bootstrap为我们的应用程序创建布局和用户界面。 因此,在终端中继续输入:

$npm install --save bootstrap

Including FusionCharts core package, it's React Component and FusionMaps package We will be using FusionCharts to render charts in our dashboard app. You can go ahead and check out more about it here.

包括FusionCharts核心程序包,React Component和FusionMaps程序包我们将使用FusionCharts在仪表板应用程序中呈现图表。 您可以继续在此处查看更多信息。

There are multiple ways to install FusionCharts, for general instructions you can check out this documentation page.

有多种安装FusionCharts的方法,有关一般说明,您可以查看此文档页面

FusionCharts Direct Download You can directly download JS files from FusionCharts website using this link and include them in your application using <script> tag in /public/index.html of application.

FusionCharts 直接下载您可以使用此链接从FusionCharts网站直接下载JS文件,并使用应用程序的/public/index.html<script>标记将它们包含在您的应用程序中。

Using NPM (we will be using this!) So, in the terminal, navigate to our working directory i.e. ecommerce-dashboard and enter:

使用NPM (我们将使用它!)因此,在终端中,导航到我们的工作目录,即ecommerce-dashboard并输入:

$npm install --save fusioncharts

To render maps, we will need also FusionMaps definition files. There are multiple ways to install them, for more details you can check out this developer documentation page.

要渲染地图,我们还需要FusionMaps定义文件。 有多种安装方法,有关更多详细信息,请查看此开发人员文档页面

Direct Download You can directly download JS files for all the maps from FusionCharts website using this link and include the respective map file which you want to render using <script> tag in /public/index.html of application.

直接下载您可以使用此链接从FusionCharts网站直接下载所有地图的JS文件,并在应用程序的/public/index.html中包含要使用<script>标记渲染的相应地图文件。

Using NPM (we will be using this!) So, in the terminal, navigate to our working directory i.e. ecommerce-dashboard and enter:

使用NPM (我们将使用它!)因此,在终端中,导航到我们的工作目录,即ecommerce-dashboard并输入:

$npm install --save fusionmaps

FusionCharts also provides a lightweight and simple-to-use component for React that can be used to add JS charts in react app without any hassle. We will be using it in our app. Let’s install it using the command below:

FusionCharts还为React提供了一个轻量级且易于使用的组件 ,可用于在React应用中添加JS图表,而不会带来任何麻烦。 我们将在我们的应用程序中使用它。 让我们使用以下命令进行安装:

$npm install --save react-fusioncharts

You can learn more about FusionCharts react component using this link. Now that we have included all the dependencies, we will go ahead and set-up Google Sheets API.

您可以使用此链接了解有关FusionCharts react组件的更多信息。 现在,我们已经包含了所有依赖项,我们将继续设置Google Sheets API。

Google Sheets API Setup We’ll start by creating a new project for our application on developer console to fetch data from Google Sheets. For this article, I’m naming it ecommerce-dashboard.

Google Sheets API设置首先,我们将在开发人员控制台上为我们的应用程序创建一个新项目,以从Google Sheets中获取数据。 对于本文,我将其命名为ecommerce-dashboard

You can create a new project through this link.

您可以通过此链接创建一个新项目。

Once the project is created, you’ll be redirected to Google Developer API dashboard. Now, we will enable Google Sheets API for our app. For this in the APIs box, click “Go to APIs overview”. Once you click “Enable APIs and Services” you’ll be presented with the API Library and we’ll go ahead and search for “Google Sheets API”.

创建项目后,您将被重定向到Google Developer API信息中心。 现在,我们将为我们的应用启用Google Sheets API。 为此,请在“ API”框中单击“转到API概述”。 点击“启用API和服务”后,系统会向您显示API库,我们将继续搜索“ Google Sheets API”。

Once you find it, click “Enable” and after it is processed you should be seeing the page below.

找到它后,单击“启用”,处理完成后,您应该会看到下面的页面。

In the sidebar, head over to “Credentials” and click the “Create credentials” button and select “API Key”. Click the “Restrict Key” and set a name for it (I’ve named it as EcommerceDashboardAPIKey).

在边栏中,转到“凭据”,然后单击“创建凭据”按钮,然后选择“ API密钥”。 单击“限制键”并为其设置一个名称(我将其命名为EcommerceDashboardAPIKey )。

Save the key generated, as we’ll need it to pull data from our Google Sheet later.

保存生成的密钥,因为稍后我们需要它来从Google表格中提取数据。

Under “API Restrictions” select the “Google Sheets API” and save. Now, we are good to go for our next step where we’ll connect Google Sheets API and fetch the data.

在“ API限制”下,选择“ Google Sheets API”并保存。 现在,我们可以继续进行下一步了,我们将连接Google Sheets API并获取数据。

连接Google表格和获取数据 ( Connecting Google Sheets and Fetching data )

Now, let’s head to the Google Sheet that we will be using for this application. Here’s a screenshot of how it looks. I’ve collected random data for 13 months focusing on KPIs of for online retail business.

现在,让我们转到将用于此应用程序的Google表格。 这是它外观的屏幕截图。 我已经收集了13个月的随机数据,重点是在线零售业务的KPI。

Now, we will make the sheet public so that anyone can see it. For this in the File menu, click “Share”. Once you click “Get shareable link” and after it’s processed, the sheet will be shared for “Anyone with link can view” access by default.

现在,我们将工作表公开,以便任何人都可以看到它。 为此,在文件菜单中,单击“共享”。 单击“获取可共享的链接”后,在处理完该表后,默认情况下将共享该表以供“具有链接的任何人都可以查看”访问权限。

Since we want to make the sheet public, head over to “Anyone with link can view” and click the “More” option in the drop-down. Select “On - Public on the web” option and save.

由于我们要公开该工作表,因此转到“任何具有链接的人都可以查看”,然后单击下拉菜单中的“更多”选项。 选择“在-网络上公开”选项并保存。

You can access the sheet I’ll be using from this link. We’ll keep a note of the spreadsheet ID (this can be found in the URL for Google Sheets, for me its 1sCgmzBIq2K9jUckLuYSWbDq4CuNUfdtuE6a5xI3I5Hw).

您可以从此链接访问要使用的工作表。 我们会记下电子表格ID(可以在Google表格的URL中找到,对我来说是1sCgmzBIq2K9jUckLuYSWbDq4CuNUfdtuE6a5xI3I5Hw )。

We will be using batchGet method for our dashboard app. It returns one or more ranges of values from a spreadsheet. You can learn more about it here.

我们将为我们的仪表板应用程序使用batchGet方法。 它从电子表格返回一个或多个值范围。 您可以在此处了解更多信息。

Let’s open up our working directory (ecommerce-dashboard for me) in a code editor and create a new file with name config.js. Input your API key and spreadsheet ID in it.

让我们在代码编辑器中打开工作目录(对我来说是ecommerce-dashboard ),并创建一个名为config.js的新文件。 在其中输入您的API密钥和电子表格ID。

export default {
    apiKey: 'YOUR-API-KEY',
    spreadsheetId: '1sCgmzBIq2K9jUckLuYSWbDq4CuNUfdtuE6a5xI3I5Hw'
}

Now let’s head over to App.js file. We’ll be adding everything directly to App.js, which came with the boilerplate. This is not ideally the best architecture, rather just a display of the concepts.

现在让我们转到App.js文件。 我们将直接将所有内容添加到样板随附的App.js 。 理想情况下,这不是最佳的体系结构,而只是概念的展示。

Now let’s look at the steps below to show how I’ll connect our dashboard app to Google Sheets API and fetch data from it:

现在,让我们看看以下步骤,以展示如何将仪表板应用程序连接到Google Sheets API并从中获取数据:

  1. Import config.js we created using the code below and declare a variable with request URL for Google Sheets API.

    导入我们使用以下代码创建的config.js并使用Google Sheets API的请求URL声明一个变量。
import config from './config';

const url = `https://sheets.googleapis.com/v4/spreadsheets/${ config.spreadsheetId }/values:batchGet?ranges=Sheet1&majorDimension=ROWS&key=${ config.apiKey }`;
  1. Now, we’ll set an empty array in this.state as shown in the code below:

    现在,我们将在this.state设置一个空数组,如下面的代码所示:
constructor() {
    super();
    this.state = {
     items:[]
    };
  }
  1. Fetch the JSON data from React’s lifecycle componentDidMount method:

    从React的生命周期componentDidMount方法获取JSON数据:
componentDidMount() {
    fetch(url).then(response => response.json()).then(data => {
      let batchRowValues = data.valueRanges[0].values;

      const rows = [];
      for (let i = 1; i < batchRowValues.length; i++) {
        let rowObject = {};
        for (let j = 0; j < batchRowValues++[++i].length; j++) {
          rowObject[batchRowValues[0][j]] = batchRowValues[i][j];
        }
        rows.push(rowObject);
      }

      this.setState({ items: rows });
    });
}

Awesome! Now that we have established a connection with our Google Sheets, we will start building the layout for our dashboard.

太棒了! 现在,我们已经与Google表格建立了联系,我们将开始为仪表板构建布局。

Note: You can verify the connection by logging the items variable inside state.

注意 :您可以通过在状态内部记录items变量来验证连接。

建立仪表板布局 ( Building the Dashboard Layout )

We’ll be using Bootstrap to build the layout for our application. We have already installed it, now let’s import it in our application. Head over to index.js and import the Bootstrap’s CSS file:

我们将使用Bootstrap构建应用程序的布局。 我们已经安装了它,现在将其导入我们的应用程序中。 转到index.js并导入BootstrapCSS文件:

import "bootstrap/dist/css/bootstrap.css";

Now let’s divide our application’s layout into 4 parts:

现在,将应用程序的布局分为四个部分:

  1. Navigation Section

    导航部分
  2. KPI Section

    KPI部分
  3. KPI and Mini Charts Section

    KPI和迷你图表部分
  4. Charts Section

    图表部分

We will also over-write some of the default styles provided by Bootstrap using our own CSS that will be present in the file style.css which is included in index.js file.

我们还将使用自己CSS覆盖Bootstrap提供的一些默认样式,这些样式将出现在index.js文件中包含的style.css文件中。

Creating the Navigation Section To create this, we will consume nav component provided by Bootstrap. You can check it out here. Below is the HTML snippet for the same:

创建导航部分要创建此部分,我们将使用Bootstrap提供的nav组件。 您可以在这里查看 。 以下是相同HTML代码段:

<Nav className="navbar navbar-expand-lg fixed-top is-white is-dark-text">
      <div className="navbar-brand h1 mb-0 text-large font-medium">
        Online Retail Dashboard
      </div>
      <div className="navbar-nav ml-auto">
        <div className="user-detail-section">
          <span className="pr-2">Hi, Sean</span>
          <span className="img-container">
          <-- add image uri here -->
          <img src="" className="rounded-circle" alt="user" />
        </span>
      </div>
  </div>
</Nav>

Since we have two navigation sections in our application we will repeat the process above and customize the second navigation section using CSS.

由于我们的应用程序中有两个导航部分,因此我们将重复上述过程,并使用CSS自定义第二个导航部分。

Now, that our navigation section is ready, we’ll create a container to house the next three sections of our application. Here’s the HTML snippet for the same:

现在,导航部分已经准备就绪,我们将创建一个container来容纳应用程序的下三个部分。 这是相同HTML代码段:

<div className="container-fluid">
<!-- kpi section -->

<!-- kpi + mini charts section -->

<!-- charts section -->
</div>

You can learn more about Bootstrap containers here.

您可以在此处了解有关Bootstrap容器的更多信息。

Creating the KPI Section To create this, we’ll use rows, columns and cards provided by Bootstrap to create the layout for our KPI section as shown in the image above. Below is the HTML snippet for the same:

创建KPI部分要创建此KPI部分 ,我们将使用Bootstrap提供的行,列和卡片为KPI部分创建布局,如上图所示。 以下是相同HTML代码段:

<div className="row">
  <div className="col-lg-3 col-sm-6">
    <div className="card">
      <div className="card-heading">
        <div>
          Total Revenue
        </div>
      </div>
      <div className="card-value">
        <span>$</span>

      </div>
    </div>
  </div>
</div>

The above snippet will create one KPI card (for “Total Revenue”). Similarly, we will create cards for all 4 KPIs that we want to showcase. You can learn more about rows, columns and cards from Bootstrap’s documentation using this link.

上面的代码片段将创建一张KPI卡(“总收入”)。 同样,我们将为要展示的所有4个KPI创建卡片。 您可以使用此链接从Bootstrap的文档中了解有关行,列和卡的更多信息。

Creating the KPI and Mini-Charts Section To create this, we’ll again use rows, columns and cards provided by Bootstrap as we did in the previous step to create the layout for our KPI section as shown in the image above. Below is the HTML snippet for the same:

创建KPI和Mini - Charts部分要创建它,我们将再次使用Bootstrap提供的行,列和卡片,就像在上一步中一样,为KPI部分创建布局,如上图所示。 以下是相同HTML代码段:

<div className="row">
  <div className="col-md-4 col-lg-3">
    <!-- kpi layout as in previous step -->
  </div>
  <div className="col-md-8 col-lg-9">
    <div className="card">
      <div className="row">
        <!-- row to include all mini-charts -->
        <div className="col-sm-4">
          <div className="chart-container">
            <!-- chart will come here -->
          </div>
        </div>
      </div>
    </div>
  </div>
</div>

The above snippet will add one KPI to the left and one mini-chart section inside the card to the right. Similarly, we will add other two mini-charts layout inside the card as shown in the dashboard snapshot at the beginning of the article.

上面的代码段将在左侧添加一个KPI,在右侧添加一个迷你图表部分。 同样,我们将在卡片内添加其他两个微型图表布局,如本文开头的仪表板快照所示。

Creating the Mini-Charts Section To create this, we’ll again use rows, columns and cards provided by Bootstrap as we did in previous steps to create the layout for our charts as shown in the dashboard snapshot at the beginning of the article. Below is the HTML snippet for the same:

创建迷你 图表部分要创建此部分,我们将按照前面步骤中的步骤再次使用Bootstrap提供的行,列和卡片,以创建图表的布局,如本文开头的仪表板快照所示。 以下是相同HTML代码段:

<div className="row">
  <div className="col-md-6">
    <div className="card">
      <div className="chart-div"></div>
      <!-- chart will come here -->
    </div>
  </div>
</div>

The above snippet will add one card. We can repeat the above step to create another card. If you’ve followed the above steps till now you should have a similar layout as in the dashboard snapshot at the beginning of the article. If not - don’t worry I’ll be adding the link to Github repo for this dashboard at the end of this tutorial.

上面的代码段将添加一张卡。 我们可以重复上述步骤来创建另一个卡。 如果您已按照上述步骤进行操作,则您现在应该具有与本文开头的仪表板快照类似的布局。 如果不是这样,请放心,我将在本教程的结尾为该仪表板添加指向Github存储库的链接。

创建关键绩效指标 ( Creating KPI’s )

Now that our layout is ready, we will define functionality for elements and feed data to them from Google Sheets. For this, we will define a function called getData in our component which will take the month as an argument to de-structure google sheets data present in the app’s state.

现在我们的布局已经准备就绪,我们将定义元素的功能并从Google表格中向其提供数据。 为此,我们将在组件中定义一个名为getData的函数,该函数将以月份为参数来解构应用状态下存在的Google表格数据。

Now, we’ll loop through the data to calculate values as needed for KPIs. Below is the code to create the KPI for “Revenue from Amazon”.

现在,我们将遍历数据以计算KPI所需的值。 下面是为“来自亚马逊的收入”创建KPI的代码。

getData = arg => {
    // google sheet data
    const arr = this.state.items;
    const arrLen = arr.length;

    // kpi's
    // amazon revenue
    let amRevenue = 0;

    for (let i = 0; i < arrLen; i++) {
        if (arg === arr[i]["month"]) {
          if (arr[i]["source"] === "AM") {
            amRevenue += parseInt(arr[i].revenue);
          } 
        }
    }

    // setting state
    this.setState({
        amRevenue: amRevenue
    });
};

Similarly, we will define variables for other KPIs and assign a value to them upon looping through the data using the above code snippet.

同样,我们将为其他KPI定义变量,并使用上述代码片段在遍历数据时为它们分配一个值。

Once the value for KPI is calculated we will set its value in app’s state to consume it in the layout as needed. Below is an example to consume the value from the state.

一旦计算出KPI的值,我们将在应用程序的状态下设置其值,以根据需要在布局中使用它。 下面是一个使用状态值的示例。

<div className="row">
  <div className="col-lg-3 col-sm-6">
    <div className="card">
      <div className="card-heading">
        <div>
          Revenue from Amazon
        </div>
      </div>
      <div className="card-value">
        <span>$</span>
        {this.state.amRevenue}
      </div>
    </div>
  </div>
</div>

创建图表 ( Creating Charts )

Now that our KPI’s are ready, we will loop through data and prepare JSON arrays for our charts and use FusionCharts and its React component to render the charts.

现在我们的KPI已经准备就绪,我们将遍历数据并为图表准备JSON数组,并使用FusionCharts及其React组件来呈现图表。

For this, we will be using getData function that we created in the previous step.

为此,我们将使用在上一步中创建的getData函数。

Now, we will create a file called chart-theme.js to create a theme for charts that we will be using. This theme will have cosmetics options for all our charts so that we don’t have to define them each time we create one. Here’s how it looks like:

现在,我们将创建一个名为chart-theme.js的文件,为将要使用的图表创建一个主题。 该主题将为所有图表提供化妆品选项,因此我们不必在每次创建图表时都定义它们。 看起来像这样:

window.FusionCharts.register("theme", {
  name: "ecommerce",
  theme: {
    base: {
      chart: {
        bgAlpha: "0",
        canvasBgAlpha: "0",
        baseFont: "basefont-regular",
        baseFontSize: "14",
        baseFontBold: "0",
        chartBottomMargin: "0",
        chartTopMargin: "0",
        chartLeftMargin: "0",
        chartRightMargin: "0",
        canvasBottomMargin: "0",
        canvasTopMargin: "0",
        canvasRightMargin: "0",
        canvasLeftMargin: "0",
        showBorder: "0",
        showCanvasBorder: "0",
        baseFontColor: "#ffffff",
        captionFontBold: "0",
        captionFontSize: "14",
        subCaptionFontSize: "14",
        tooltipColor: "#ffffff",
        tooltipBgColor: "#000000",
        tooltipBgAlpha: "60",
        tooltipPadding: "5",
        toolTipBorderAlpha: "10",
        toolTipBorderRadius: "3",
        showValues: "0",
        legendBgAlpha: "0",
        legendBorderAlpha: "0",
        legendBorderThickness: "0"
      }
    },
    bar2d: {
      chart: {
        placeValuesInside: "0",
        usePlotGradientColor: "0",
        showAlternateVGridColor: "0",
        chartLeftMargin: "5",
        canvasLeftMargin: "5",
        divLineAlpha: "10",
        divLineColor: "#ffffff",
        captionFontColor: "#8091ab",
        paletteColors: "#1D91C0",
        valuePadding: "5",
        yAxisName: "Orders",
        yAxisNameAlpha: "50",
        yAxisNameFontSize: "12",
        yAxisNamePadding: "20",
        valueFontBold: "0",
        valueFontSize: "12",
        plotToolText: "<div>$label<br><b>$value orders</b>",
        captionAlignment: "left",
        captionPadding: "20"
      }
    },
    doughnut2d: {
      chart: {
        captionFontSize: "14",
        captionFontColor: "#8091ab",
        showLabels: "0",
        showValues: "0",
        use3DLighting: "0",
        showPlotBorder: "0",
        defaultCenterLabel: "75%",
        pieRadius: "45",
        doughnutRadius: "33",
        showTooltip: "0",
        enableRotation: "0",
        enableSlicing: "0",
        startingAngle: "90"
      }
    },
    geo: {
      chart: {
        captionFontSize: "14",
        captionFontColor: "#8091ab",
        legendScaleLineThickness: "0",
        legendaxisborderalpha: "0",
        legendShadow: "0",
        plotFillAlpha: "85",
        showBorder: "1",
        borderColor: "#ffffff",
        borderThickness: "0.3",
        nullEntityColor: "#17202e",
        nullEntityAlpha: "50",
        entityFillHoverColor: "#17202e",
        captionAlignment: "left",
        entityToolText: "<div>$lname<br><b>$value orders</b>",
        chartLeftMargin: "40"
      }
    }
  }
});

You can learn more about FusionCharts themes from this documentation page.

您可以从本文档页面了解有关FusionCharts主题的更多信息。

Now let’s begin with creating mini-charts. We will be using Doughnut Chart (doughtnut2d) for this. You can learn more about this chart here.

现在让我们开始创建迷你图表。 我们将为此使用“甜甜圈图”( doughtnut2d )。 您可以在此处了解有关此图表的更多信息。

getData = arg => {
  // google sheets data
  const arr = this.state.items;
  const arrLen = arr.length;
  let purchaseRate = 0;
  for (let i = 0; i < arrLen; i++) {
    if (arg === arr[i]["month"]) {
      purchaseRate += parseInt(arr[i].purchase_rate / 3);
    }
  }
  // setting state
  this.setState({
    purchaseRate: purchaseRate
  });
};

Now that our mini-chart’s value is set in the state we will initiate chart instance via FusionCharts’ React component and form JSON array to render the chart. Below is code for the same:

现在,我们已将微型图表的值设置为状态,我们将通过FusionCharts的React组件启动图表实例,并形成JSON数组以呈现图表。 下面是相同的代码:

<div className="chart-container full-height">
    <ReactFC
      {...{
        type: "doughnut2d",
        width: "100%",
        height: "100%",
        dataFormat: "json",
        dataSource: {
          chart: {
            caption: "Purchase Rate",
            theme: "ecommerce",
            defaultCenterLabel: `${this.state.purchaseRate}%`,
            paletteColors: "#3B70C4, #000000"
          },
          data: [
            {
              label: "active",
              value: `${this.state.purchaseRate}`
            },
            {
              label: "inactive",
              alpha: 5,
              value: `${100 - this.state.purchaseRate}`
            }
          ]
        }
      }}
    />
</div>

This will create a mini-chart for “Purchase Rate”. Similarly, we can follow the above steps to create the other two mini-charts.

这将为“购买率”创建一个迷你图表。 同样,我们可以按照上述步骤创建其他两个迷你图表。

Now, let’s move to our charts section.

现在,让我们转到图表部分。

For this, we will define an empty array inside getData function and push data to it, after looping through Google Sheets data. Below is code snippet for the same:

为此,我们将在遍历Google表格数据之后,在getData函数内定义一个空数组并将数据推送到其中。 以下是相同的代码段:

getData = arg => {
  // google sheets data
  const arr = this.state.items;
  const arrLen = arr.length;

  // order trend by brand
  let ordersTrendStore = [];

  for (let i = 0; i < arrLen; i++) {
    if (arg === arr[i]["month"]) {
      if (arr[i]["source"] === "AM") {
        ordersTrendStore.push({
          label: "Amazon",
          value: arr[i].orders,
          displayValue: `${arr[i].orders} orders`
        });
      } else if (arr[i]["source"] === "EB") {
        ordersTrendStore.push({
          label: "Ebay",
          value: arr[i].orders,
          displayValue: `${arr[i].orders} orders`
        });
      } else if (arr[i]["source"] === "ET") {
        ordersTrendStore.push({
          label: "Etsy",
          value: arr[i].orders,
          displayValue: `${arr[i].orders} orders`
        });
      }
    }
  }

  // setting state
  this.setState({
    ordersTrendStore: ordersTrendStore
  });
};

Now that our chart’s data array is ready, we will initiate the charts instance via FusionCharts’ React component and form JSON array to render the chart.

现在我们的图表数据数组已准备就绪,我们将通过FusionCharts的React组件启动图表实例,并形成JSON数组以呈现图表。

<div className="chart-container">
    <ReactFC
      {...{
        type: "bar2d",
        width: "100%",
        height: "100%",
        dataFormat: "json",
        dataSource: {
          chart: {
            theme: "ecommerce",
            caption: "Orders Trend",
            subCaption: "By Stores"
          },
          data: this.state.ordersTrendStore
        }
      }}
    />
</div>

This will create Bar Chart (bar2d) chart in our application. You can learn more about this chart here.

这将在我们的应用程序中创建条形图( bar2d )图表。 您可以在此处了解有关此图表的更多信息。

Now that our first chart is ready, we will create our last chart which is a USA region map. For this, we have to import respective map definition file from FusionMaps package that we installed earlier. Below is code for the same:

现在我们的第一个图表已经准备好,我们将创建我们的最后一个图表,即美国区域地图。 为此,我们必须从我们先前安装的FusionMaps包中导入相应的地图定义文件。 下面是相同的代码:

import Maps from "fusioncharts/fusioncharts.maps";
import USARegion from "fusionmaps/maps/es/fusioncharts.usaregion";

To render the map, we will again define an empty array inside getData function and push data to it corresponding to respective ID which can be taken from this map specification sheet, after looping through Google Sheets data. Below is code snippet for the same:

为了渲染地图,我们将在getData函数中再次定义一个空数组,并将对应于相应ID的数据推送到该数组,该ID可在遍历Google表格数据之后从此地图规范表获取。 以下是相同的代码段:

getData = arg => {
  // google sheets data
  const arr = this.state.items;
  const arrLen = arr.length;

  // order trend by region
  let ordersTrendRegion = [];
  let orderesTrendnw = 0;
  let orderesTrendsw = 0;
  let orderesTrendc = 0;
  let orderesTrendne = 0;
  let orderesTrendse = 0;
  for (let i = 0; i < arrLen; i++) {
      orderesTrendnw += parseInt(arr[i].orders_nw);
      orderesTrendsw += parseInt(arr[i].orders_sw);
      orderesTrendc += parseInt(arr[i].orders_c);
      orderesTrendne += parseInt(arr[i].orders_ne);
      orderesTrendse += parseInt(arr[i].orders_se);
    }
  ordersTrendRegion.push({
    id: "01",
    value: orderesTrendne
  }, {
    id: "02",
    value: orderesTrendnw
  },{
    id: "03",
    value: orderesTrendse
  }, {
    id: "04",
    value: orderesTrendsw
  }, {
    id: "05",
    value: orderesTrendc
  });

  // setting state
  this.setState({
    ordersTrendRegion: ordersTrendRegion
  });
};

Now that our map’s data array is ready, we will initiate the charts instance via FusionCharts’ React component and form JSON array to render the map.

现在我们的地图数据数组已准备就绪,我们将通过FusionCharts的React组件启动图表实例,并形成JSON数组以呈现地图。

<div className="chart-container">
    <ReactFC
      {...{
        type: "usaregion",
        width: "100%",
        height: "100%",
        dataFormat: "json",
        dataSource: {
          chart: {
            theme: "ecommerce",
            caption: "Orders Trend",
            subCaption: "By Region"
          },
          colorrange: {
            code: "#F64F4B",
            minvalue: "0",
            gradient: "1",
            color: [
              {
                minValue: "10",
                maxvalue: "15",
                code: "#EDF8B1"
              },
              {
                minvalue: "15",
                maxvalue: "20",
                code: "#18D380"
              }
            ]
          },
          data: this.state.ordersTrendRegion
        }
      }}
    />
</div>

This will render our map. You can know more about maps and how to use them here.

这将渲染我们的地图。 您可以在这里了解更多有关地图以及如何使用它们的信息

We will now call getData function with Jan 2019 as an argument from componentDidMount method so that our dashboard loads with Jan 2019 data present in Google Sheet by default. If you’ve followed the above steps till now you should have a functional dashboard as in the image below:

现在,我们将使用componentDidMount方法的参数调用Jan 2019 getData函数,以便默认情况下我们的仪表板加载Google Sheet中存在的2019年1月数据。 如果您已按照上述步骤进行操作,那么您现在应该拥有一个功能仪表板,如下图所示:

I hope this tutorial will help you create this dashboard using Google Sheets! Now you can work your magic on adding more UI elements, charts, KPIs and more features.

希望本教程能够帮助您使用Google表格创建此信息中心! 现在,您可以运用魔术来添加更多UI元素,图表,KPI和更多功能。

I have added some styling and functionality myself and also used Styled Components for ease. You can know more about Styled Components here. And, you can check out the final live dashboard here.

我自己添加了一些样式和功能,并且还轻松使用了样式化组件。 您可以在此处了解有关样式化组件的更多信息。 并且,您可以在此处查看最终的实时信息中心。

For any references, you can check out the source code from this Github repository. If you have any questions/feedback, comment below or yell at me on Twitter!

对于任何参考,您可以从此Github存储库中签出源代码。 如果您有任何疑问/反馈,请在下面评论或在Twitter上大喊大叫!

翻译自: https://scotch.io/tutorials/building-an-online-retail-dashboard-in-react

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值