Let’s drawing charts in React-Native without any library

Data visualization will make your App more outstanding, but there is no way to use d3 or SVG directly in react-native. Although react-native-svg could be useful, but it only support for iOS, so what if you want to make an App for both platforms?

Recently I was making an App for NBA. As an NBA huge fan, I really cares the data of the player and we always judging a player’s performance by his data. So how to demonstrate those data? here is my design for player’s page:

Supporting for both platforms is one of my initial goals before making this App. For data visualization, WebView can be an answer but it needs you to build a server to supply the content of the WebView which I really can’t accept.

Fortunately, when I found react-native has an API called Animated and the Style of the <View /> supports border-radius and position, I thought I can make these charts out without any other libraries. And here, I will show you what I have done without too many detailed explanation. Because I think you can check the source code and every detail in the Github(I made comments in my source code), but before that, it’s important to see what it could be.

Bar chart

For the first bar chart, here is the simplified code for the example:

Pretty easy right? Just making use of Animated can help you to make a dynamic bar chart, you can check the completed code for the chart, and the effect is showed in the following GIF:

Column chart

For the column chart, it is complicated than the previous bar chart,the whole column chart is based on the <ScrollView>:

For each column, it composed with two parts which I call empty part and entity part, I stack them after calculation to make a completed column. And for those negative column, I just use css to revert them:

transform: [{ rotate: ‘180deg’}]

I also want to have a tooltip when I press upon the column, here I use <TouchableHighlight /> to help me:

You can check the source code of generating each column and the following GIF is the final effect:

The column chart is not perfect because the tooltip can only be triggered by press , which means that the user can’t hover through each column and see the extra content supplied by the tooltip of every column.

Further

Directly building charts in react-native is really convenient and the more important thing is that it supports for both iOS and Android. You can make use of CSS to build the appearance of chart and Animated APIfor the animation, you can also take some try on building a line chart or circle chart directly in react-native, however, it could be more challenging.

If you want to build some really complicated charts, I suggest you to use WebView and d3 or react-native-svg if you only need to support iOS. But if you just need some simple charts, why not try to build one step by step on your own, that could be really funny :)