Just recently I finished the first story in upcoming series about linear algebra. And right before starting the new one I had a thought that would be cool to develop a React project showcasing examples from the series… GitHub repository can be found there and commit with the state of this story there.
Since on the moment of writing, there is only one story that covers basic operations on vectors in series. It would be enough for now to implement components that will help us to render two-dimensional grid and vectors as arrows. The end result for this part shown below, also you can play with it here.
Create React App
There is an entire story about best practices of how to start to react project, but for this case, we will go with as little libraries as possible and with simplest setup possible.
npm install --save react-sizeme styled-components
The first library will be used to re render the Grid component when its size changes and the second one to make styling of components easier. To use linear-algebra library we are developing in series, we need to reference it in package.json.
For each example we have it is own component in views folder. From index.js we export an object where the key is the name of an example and value is component.
Then we can import this object in the main component and list all of its keys in the menu. After the user selects an example in the menu, the component state will be updated, and the new view will be rendered.
To render vectors and other stuff from upcoming stories we need to have a nice component that will provide the function to project coordinates from the format we are accustomed to — when (0,0) on the center of the view and the y-axis pointing up to SVG coordinates where (0,0) is in top-left corner and y- axis pointing down.
To catch the moment when the container of the Grid changes its size we wrap our component with function from the react-size library.
To make it easier to use the grid in different examples we write a GridExample component that receives two parameters — function that will render information, such as names and components of vectors, and function, that will render content on the grid, such as arrows.
Then we can use this component in our views. Let’s take a look at an example showing vectors addition.
Arrow consists of three SVG element — line to represent arrow, polygon to represent the head of an arrow, and text to show the name of a vector. To place an arrow the right way relative to the grid we receive the project function.
A lot of interesting stuff can be done by combining React and SVG, and in this series, we are going to add more features to this project to visualize examples that are coming next. There is also a similar article, about making of sophisticated bar charts with React and SVG, you can check out it here.
Reach the next level of focus and productivity with increaser.org.