banner



How To Use Json Data In Reactjs

Introduction

When building applications in React, we oft need to work with JSON data. This data could come from third party APIs or be read from external files. In this guide, we volition piece of work on a code example to load the JSON data from a file and render it inside a React component.

Use Example

Say you have a data set in JSON format containing information on financial stocks from multiple companies. Each stock has metadata associated with information technology. Your goal is to read that data from an external file and render it on the spider web page in a tabular format, as shown below.

Stock Tracker

Set React App

Open your concluding and run these commands to utilize Create React App to get a sample app running on your machine.

                                  one                  npx create-react-app load-json-data                                    two                  3cd load-json-data                  iv                  5yarn start                              

sh

Now, to run the app in the development mode, open http://localhost:3000 in your browser. You should see the sample app running with a React logo.

Add together JSON Information to a File

Create a file in your projection at location src/data.js and add the data beneath in your data.js file.

                                  one                  export                                                      const                                      stockData                                    =                                                      [                                                      2                                                      {                                                      3                                      company                  :                                                      "Twitter Inc"                  ,                                                      4                                      ticker                  :                                                      "TWTR"                  ,                                                      5                                      stockPrice                  :                                                      "22.76 USD"                  ,                                                      six                                      timeElapsed                  :                                                      "five sec ago"                  ,                                                      7                                                      }                  ,                                                      8                                                      {                                                      9                                      company                  :                                                      "Foursquare Inc"                  ,                                                      10                                      ticker                  :                                                      "SQ"                  ,                                                      xi                                      stockPrice                  :                                                      "45.28 USD"                  ,                                                      12                                      timeElapsed                  :                                                      "10 sec ago"                  ,                                                      13                                                      }                  ,                                                      14                                                      {                                                      fifteen                                      visitor                  :                                                      "Shopify Inc"                  ,                                                      16                                      ticker                  :                                                      "Store"                  ,                                                      17                                      stockPrice                  :                                                      "341.79 USD"                  ,                                                      eighteen                                      timeElapsed                  :                                                      "3 sec ago"                  ,                                                      19                                                      }                  ,                                                      xx                                                      {                                                      21                                      company                  :                                                      "Sunrun Inc"                  ,                                                      22                                      ticker                  :                                                      "RUN"                  ,                                                      23                                      stockPrice                  :                                                      "nine.87 USD"                  ,                                                      24                                      timeElapsed                  :                                                      "4 sec agone"                  ,                                                      25                                                      }                  ,                                                      26                                                      {                                                      27                                      company                  :                                                      "Adobe Inc"                  ,                                                      28                                      ticker                  :                                                      "ADBE"                  ,                                                      29                                      stockPrice                  :                                                      "300.99 USD"                  ,                                                      30                                      timeElapsed                  :                                                      "10 sec ago"                  ,                                                      31                                                      }                  ,                                                      32                                                      {                                                      33                                      company                  :                                                      "HubSpot Inc"                  ,                                                      34                                      ticker                  :                                                      "HUBS"                  ,                                                      35                                      stockPrice                  :                                                      "115.22 USD"                  ,                                                      36                                      timeElapsed                  :                                                      "12 sec ago"                  ,                                                      37                                                      }                  ,                                                      38                                    ]                  ;                              

js

stockData is a JSON array containing dummy stock prices of some companies. Each JSON object within this array contains iv things:

  • Stock ticker for the company
  • Terminal updated time in seconds

Using export const allows y'all to ascertain and initialize variables that can be imported into whatever React component. In fact, you lot'll soon import stockData as a JavaScript object in the adjacent footstep.

Update App Component

It'southward time to update our <App> component considering nosotros need to return JSON data into our components. So caput to the src/App.js file and remove all the average code that came with information technology. Instead, add this slice of lawmaking to the <App> component.

                                  one                  import                                                      React                                                      from                                                      "react"                  ;                                                      2                                    import                                                      "./App.css"                  ;                                                      three                                    import                                                      {                                                      Stocks                                                      }                                                      from                                                      "./Stocks"                  ;                                                      4                  five                                    function                                                      App                  (                  )                                                      {                                                      6                                                      return                                                      (                                                      seven                                                      <                  div className                  =                  "App"                  >                                                      8                                                      <                  Stocks                                                      /                  >                                                      9                                                      <                  /                  div                  >                                                      10                                                      )                  ;                                                      xi                                    }                                                      12                  13                                    consign                                                      default                                                      App                  ;                              

js

Go to the browser and open up http://localhost:3000. Y'all will see errors in the awarding because the <App/> component wraps and returns a <Stocks/> component that doesn't exist withal. Don't worry—you will add this new component next.

Create Stocks Component

You will now add a new component inside the src directory and proper name it Stocks.js . The location of the <Stocks/> component inside your projection should be src/Stocks.js . Add together the code below to your <Stocks> component file. The code currently doesn't do annihilation except return a <div> containing the message Welcome to Stock Tracker, but you lot will extend this code presently.

                                  1                  import                                                      React                                                      from                                                      "react"                  ;                                                      2                                    import                                                      "./App.css"                  ;                                                      3                  four                                    export                                                      const                                                      Stocks                                                      =                                                      (                  )                                                      =>                                                      {                                                      5                                                      return                                                      (                                                      vi                                                      <                  >                                                      vii                                                      <                  div className                  =                  "stock-container"                  >                  Welcome                                      to                                    Stock                                                      Tracker                  <                  /                  div                  >                                                      viii                                                      <                  /                  >                                                      9                                                      )                  ;                                                      10                                    }                  ;                              

js

Add together the css class stock-container inside src/App.css file. The code within the App.css file should expect like this.

                                  ane                  .App                                                      {                                                      2                                                      text-align                  :                                      center                  ;                                                      three                                    }                                                      four                  5                                    .stock-container                                                      {                                                      6                                                      padding-left                  :                                                      3                  em                  ;                                                      vii                                                      padding-right                  :                                                      3                  em                  ;                                                      viii                                                      margin-top                  :                                                      3                  em                  ;                                                      ix                                    }                              

css

Go to the browser and open http://localhost:3000. Yous should come across the bulletin Welcome to Stock Tracker rendered on your web page, and there should not exist any errors.

Load JSON Data into Stocks Component

Now that your <Stocks> component is set up, you can become the JSON data from the src/information.js file and render it inside <Stocks> . React allows using named imports, and we can leverage that to load JSON information. And then go alee and add together this import in your src/Stocks.js file.

                                  i                  import                                                      {                                      stockData                                    }                                                      from                                                      "./data"                  ;                              

js

The next task is to iterate over the stockData array imported from the data.js file. Within your <Stocks> component, add the logic to go over every chemical element from the stockData array.

                                  1                  import                                                      React                                                      from                                                      "react"                  ;                                                      2                                    import                                                      "./App.css"                  ;                                                      iii                                    import                                                      {                                      stockData                                    }                                                      from                                                      "./data"                  ;                                                      4                  5                                    export                                                      const                                                      Stocks                                                      =                                                      (                  )                                                      =>                                                      {                                                      6                                                      return                                                      (                                                      vii                                                      <                  >                                                      8                                                      <                  div className                  =                  "stock-container"                  >                                                      9                                                      {                  stockData                  .                  map                  (                  (                  data                  ,                                      fundamental                  )                                                      =>                                                      {                                                      10                                                      return                                                      (                                                      11                                                      <                  div key                  =                  {                  fundamental                  }                  >                                                      12                                                      {                  information                  .                  company                                                      +                                                      13                                                      " , "                                                      +                                                      xiv                                      information                  .                  ticker                                                      +                                                      fifteen                                                      " ,"                                                      +                                                      xvi                                      information                  .                  stockPrice                                                      +                                                      17                                                      ", "                                                      +                                                      xviii                                      data                  .                  timeElapsed                  }                                                      19                                                      <                  /                  div                  >                                                      20                                                      )                  ;                                                      21                                                      }                  )                  }                                                      22                                                      <                  /                  div                  >                                                      23                                                      <                  /                  >                                                      24                                                      )                  ;                                                      25                                    }                  ;                              

js

Let'southward unpack what the higher up lawmaking does. It maps over the stockData JSON assortment, which takes a callback part equally argument. This function is then called for every stock within the stockData assortment. Each time callback executes, it returns and renders a <div> displaying data for every company in a comma separated way.

Get to the browser and open http://localhost:3000. The data for all stocks should be rendered in rows on the web page. You'll render this in a tabular format in the next step. Simply for at present, you should see all your JSON information.

Brandish Stock Information In a Tabular Format

The last slice of piece of work is to render that information in a component. There are a few of changes nosotros need to make:

  1. Add a <HomePageHeader> component to display a header.
  2. Add together a <Stock> component that accepta data in props and renders a table on the web folio.
  3. Refactor the code inside the <Stocks> component to accommodate the above two changes.

Add this slice of code for the <HomePageHeader> component within the src/Stocks.js file.

                                  1                  const                                                      HomePageHeader                                                      =                                                      (                  )                                                      =>                                                      {                                                      ii                                                      return                                                      (                                                      3                                                      <                  header className                  =                  "header"                  >                                                      4                                                      <                  h2                  >                  Your                                                      Stock                                                      Tracker                  <                  /                  h2                  >                                                      5                                                      <                  /                  header                  >                                                      vi                                                      )                  ;                                                      7                                    }                  ;                              

js

The <HomePageHeader> component likewise uses a CSS form header, so we need to add it inside src/App.css .

                                  1                  .header                                                      {                                                      2                                                      background-color                  :                                                      #f4e04d                  ;                                                      3                                                      min-height                  :                                                      10                  vh                  ;                                                      four                                                      display                  :                                      flex                  ;                                                      5                                                      flex-direction                  :                                      cavalcade                  ;                                                      half-dozen                                                      marshal-items                  :                                      center                  ;                                                      7                                                      justify-content                  :                                      center                  ;                                                      viii                                                      font-size                  :                                                      calc                  (                  10                  px                                                      +                                                      2                  vmin                  )                  ;                                                      9                                                      color                  :                                                      #10375c                  ;                                                      10                                    }                              

css

The next job is to create a <Stock> component so you can abstract your code to render each stock separately. Go ahead and add this code for the <Stock> component inside your src/Stocks.js file.

                                  1                  ```js                                    iiconst Stock = ({ visitor, ticker, stockPrice, timeElapsed }) => {                  3                  if (!company) return <div />;                  4                  return (                  5                  <tabular array>                  6                  <tbody>                  7                  <tr>                  8                  <td>                  9                  <h5>{company}</h5>                  10                  </td>                  eleven                  <td>                  12                  <h5>{ticker}</h5>                  13                  </td>                  xiv                  <td>                  fifteen                  <h4>{stockPrice}</h4>                  xvi                  </td>                  17                  <td>                  eighteen                  <p>{timeElapsed}</p>                  19                  </td>                  twenty                  </tr>                  21                  </tbody>                  22                  </table>                  23                  );                  24};                  25```                              

This component accepts props and returns an HTML table for a stock with four columns rendering the company name, ticker, stock toll, and fourth dimension elapsed in seconds.

Next, practice some styling for the table. To practice then, y'all'll need the css code in hte src/App.css file.

                                  1                  ```css                                    2tabular array {                  3                  display: flex;                  4                  justify-content: center;                  5                  border: 1px solid gray;                  6}                  7td {                  viii                  edge: 1px solid gray;                  nine                  width: 30em;                  10}                  xi```                              

Finally, refactor the <Stocks> component so it can call the <HomePageHeader> and <Stock> components we just created. The code beneath renders the <Stocks> component containing a <HomePageHeader> and <Stock> for every element in within the stockData array. Instead of displaying the JSON data inside a div , yous'll now pass it as props to <Stock> component.

                                  one                  ```js                                    2export const Stocks = () => {                  3                  return (                  four                  <>                  5                  <HomePageHeader />                  six                  <div className="stock-container">                  7                  {stockData.map((data, key) => {                  eight                  return (                  9                  <div key={key}>                  10                  <Stock                  eleven                  key={fundamental}                  12                  company={information.visitor}                  13                  ticker={data.ticker}                  fourteen                  stockPrice={information.stockPrice}                  xv                  timeElapsed={data.timeElapsed}                  16                  />                  17                  </div>                  18                  );                  19                  })}                  20                  </div>                  21                  </>                  22                  );                  23};                  24```                              

Brand certain your src/Stocks.js looks exactly like this earlier y'all view the webpage in your browser.

                                  1                  ```js                                    2import React from "react";                  3import "./App.css";                  fourimport { stockData } from "./data";                  5                  6export const Stocks = () => {                  7                  render (                  eight                  <>                  9                  <HomePageHeader />                  10                  <div className="stock-container">                  11                  {stockData.map((data, key) => {                  12                  render (                  13                  <div central={fundamental}>                  14                  <Stock                  15                  key={key}                  16                  company={data.visitor}                  17                  ticker={data.ticker}                  xviii                  stockPrice={data.stockPrice}                  19                  timeElapsed={data.timeElapsed}                  twenty                  />                  21                  </div>                  22                  );                  23                  })}                  24                  </div>                  25                  </>                  26                  );                  27};                  28                  29const HomePageHeader = () => {                  30                  return (                  31                  <header className="header">                  32                  <h2>Your Stock Tracker</h2>                  33                  </header>                  34                  );                  35};                  36                  37const Stock = ({ visitor, ticker, stockPrice, timeElapsed }) => {                  38                  if (!company) return <div />;                  39                  return (                  xl                  <tabular array>                  41                  <tbody>                  42                  <tr>                  43                  <td>                  44                  <h5>{company}</h5>                  45                  </td>                  46                  <td>                  47                  <h5>{ticker}</h5>                  48                  </td>                  49                  <td>                  50                  <h4>{stockPrice}</h4>                  51                  </td>                  52                  <td>                  53                  <p>{timeElapsed}</p>                  54                  </td>                  55                  </tr>                  56                  </tbody>                  57                  </table>                  58                  );                  59};                  60```                              

Go to the browser and open http://localhost:3000. You should exist able to run across the JSON data sourced from an external file displayed in a tabular format.

Access Code on Github

The lawmaking for this awarding is bachelor on Github.

Build and Deploy this Awarding

To build the app for production to the build folder, utilise yarn build on your terminal within the root of the project. This correctly bundles React in product manner and optimizes the build for the all-time operation.

The build is minified and the filenames include the hashes. Your app is set to exist deployed!

Determination

This is i approach to loading JSON information into your React app. If your app is growing and the bundle is becoming large, you may want to consider using lawmaking splitting through dynamic imports, which improves performance of the app by loading but the code needed for initial load. Read more than about Lawmaking Splitting in the React documentation.

How To Use Json Data In Reactjs,

Source: https://www.pluralsight.com/guides/load-and-render-json-data-into-react-components

Posted by: fettermanfatabimpar1961.blogspot.com

0 Response to "How To Use Json Data In Reactjs"

Post a Comment

Iklan Atas Artikel

Iklan Tengah Artikel 1

Iklan Tengah Artikel 2

Iklan Bawah Artikel