Visualize charts with React

As a part of cloud-ready, I need to visualize the result to graphs in the frontend.

JSON data into graphs

The result file will be a json file so I need to import a json data for visualization. It was simple with the function map. This returns each object in an array, so I used it to display a table.

I chose nivo for the visualization tool. This library supports so many types of graphs and it is also easy to check codes interactively at nivo.rocks. For installation, just execute one command line below. (Note that installation with yarn is in the offical repository.)

npm install --save @nivo/core @nivo/bar

I use @nivo/bar in this case, if you want another chart, please change that part.

Conditional rendering

There is a unique rendering method in React called conditional rendering. It uses a boolean type value to select what to show.

  • Inline if with logical && operator
    {<boolean> && <component>}
    
  • Inline if-else with conditional operator
    {<boolean> ? 'on' : 'off'}
    

I used these things to switch between two charts.

<Button onClick={() => {setBar(!myBar), setTable(!myTable)}}>
  {myBar ? 'Show Table' : 'Show Bar'}
</Button>

{myTable && (
  <MyTable />
)}

{myBar && (
  <>
  <Button onClick={() => setdataA(!dataA)}>
    {dataA ? 'Show Banana' : 'Show Apple'}
  </Button>
  {dataA && (
  <MyBar sampleJson={appleList}/>
  )}
  {!dataA && (
  <MyBar sampleJson={bananaList}/>
  )}
  </>
)}

There are totally two buttons. One is for switching between table and bar and the other is visiable only for a bar to change data. Do not forget to add <> and </> at both sides to prevent the error: JSX expressions must have one parent element.

Design with Carbon

Carbon is IBM’s open source design system for products and digital experiences. You can check available React components at this website: react.carbondesignsystem.com. I organized table and button design with this. It is convenient that I do not have to write css.

The final result looks like this: gif

References


💬 Any comments and suggestions will be appreciated.

Leave a comment