DEV Community

Ryan Baxley
Ryan Baxley

Posted on • Updated on

Using Plotly to draw charts in React Native

While working on a React Native version of a web dashboard, I struggled to find a charting libary that would meet my needs. The one I tried were not performant or flexible enough, or required ejecting from Expo. Since the web charts were built using Plotly, I decided to try to get plotly.js to work in React Native.

Since plotly.js depends on a lot of browser APIs, it would not work out of the box in React Native. I thought the easiest way to get it working would be with a WebView. The first thing I did was to get a basic chart rendering by including plotly.js from their CDN with a script tag. This worked, but depended on the user being online. I wanted offline support, so I decided to try to bundle the plotly.js source code with my app, and somehow inject that into the WebView.

Getting the source code injected turned out to be a frustrating process, as I ran into a lot of issues with certain characters in the source code not being sent properly, as well as finding implementation differences between Android and iOS WebViews. Ultimately, the solution I settled on was to Base64 encode the plotly.js source code, send it to the WebView with postMessage, and decode and evaluate the code inside the WebView.

After adding the ability for my React component to call restyle/relayout functions on the chart, I was able to draw interactive, dynamic charts using Plotly, even if the device was offline! The initialization is a bit slower than other libraries (1-2 seconds before the chart is drawn), but the performance is great, and I have access to all the great features of Plotly.

This component has been working great for me, so I decided to open source it! react-native-plotly lets you use Plotly in React Native. You can see it in action on this Expo snack.

Top comments (3)

projectmanager1106 profile image

Hello @rynobax, Thanks for your post. This is Derek

I am looking for a specific chart compatible with React Native app. The chart will be exactly same to for one stock (APPL) with last 10 years data. The graph/chart needs to have the same look-n-file, transitioning/motion etc. I would like to clarify that Chart should exactly work like step chart. Could you guide me for it?


mrcflorian profile image

Using a Webview sounds a little hacky and it might hurt performance. Have you considered React Native Chart Kit?

rynobax_7 profile image
Ryan Baxley

I looked into a lot of charting libraries, but none of them met my needs. For example, that library doesn't look like it supports complex background coloring, or panning/zooming the chart.

As for performace, ignoring the initial load time, this was by far the fastest solution I came across. Most libraries I tested slowed down on hundreds of points, but plotly worked fine.