How to make Simple Line Chart using Victory in React in 5 minutes
React is a great tool to make a great web page. Sometimes you want to provide a graph with your information. An easy way to make a graph is by using Victory. I’ll start from scratch and walk you through it. I’m gonna make a chart off of how many tacos I eat each day in the week.
Now the next thing you want to do is install Victory to your project and import VictoryChart and VictoryLine to your selected file.
npm install victory
After finishing installing and importing Victory to your project, get your data and tweak it a bit to their preference. Your data has to be inside an array and each index in the array is an object. Each object should have two keys which are called ‘x’ and ‘y’ and their value for each of them. My example below between lines 8 to 17 should show you how your data should look like. I decided to place the information in the state since I’m assuming you guys are going to place the information there if you are going to be make a React Component.
Place a <VictoryLine> tag in your return section of your file and wrap it with a <VictoryChart> tag. To add data to your page, you need to set it as a prop as data inside of your <VictoryLine> tag. And KAZAM you have now made a simple line chart
If you follow my instructions properly then your graph should look like below.
Now the graph is pretty basic to look at so lets make it extra nice since you realized on how fast it takes to make a chart through Victory. Lets make the stroke color #02B875(Medium green color). To do this add a style prop to your <VictoryLine> tag. Now make the style prop equal an object that has a key named data. Inside of that data key make its value equal an object with its key equal stroke and its value equaling the color you want.
Look at that! Now your graph looks twice as cool with that green stroke color! Did you want your user to see why each coordinate had that value? You can also do that in victory using VictoryVoroniContainor. First add a label to each coordinate in your array. Then import VictoryVoroniContainor into your JS file. Inside of your <VictoryChart> tag add a label prop and make it equal a <VictoryVoroniContainor> tag with one prop equal named label. Label works like a map method. On each element you want to return label key of each element. It’s a little hard to explain but just follow my code as reference below.
Ok that looks nasty, lets fix that. To make it look only the coordinate that your mouse is hovering over, import VictoryTooltip from victory and inside of the <VictoryLine> tag add a prop named and labelComponent and make it equal to a <VictoryTooltip> tag.
Now you have made a simple and interactive chart in less than 5 minutes! For reference, the whole code is written below.