Visx is a library that lets us add graphics to our React app easily.
In this article, we’ll look at how to use it to add polygons into our React app.
Install Required Packages
We have to install a few modules.
To get started, we run:
npm i @visx/gradient @visx/group @visx/responsive @visx/scale @visx/shape
to install the packages.
Add Polygons
To add the polygons, we write:
import React from "react";
import { Polygon } from "@visx/shape";
import { Group } from "@visx/group";
import { scaleBand } from "@visx/scale";
import { GradientPinkRed } from "@visx/gradient";
export const background = "#7f82e3";
const polygonSize = 25;
const defaultMargin = { top: 10, right: 10, bottom: 10, left: 10 };
const polygons = [
{
sides: 3,
fill: "rgb(174, 238, 248)",
rotate: 90
},
{
sides: 4,
fill: "lightgreen",
rotate: 45
},
{
sides: 6,
fill: "rgb(229, 130, 255)",
rotate: 0
},
{
sides: 8,
fill: "url(#polygon-pink)",
rotate: 0
}
];
const yScale = scaleBand({
domain: polygons.map((p, i) => i),
padding: 0.8
});
const Example = ({ width, height, margin = defaultMargin }: PolygonProps) => {
yScale.rangeRound([0, height - margin.top - margin.bottom]);
const centerX = (width - margin.left - margin.right) / 2;
return (
<svg width={width} height={height}>
<rect width={width} height={height} fill={background} rx={14} />
<GradientPinkRed id="polygon-pink" />
{polygons.map((polygon, i) => (
<Group
key={`polygon-${i}`}
top={(yScale(i) || 0) + polygonSize / 2}
left={margin.left + centerX}
>
<Polygon
sides={polygon.sides}
size={polygonSize}
fill={polygon.fill}
rotate={polygon.rotate}
/>
</Group>
))}
</svg>
);
};
export default function App() {
return (
<div className="App">
<Example width={500} height={300} />
</div>
);
}
The background
variable has the background’s color.
polygonSize
is the size of each polygon in pixels.
We create the polygons
array with the properties of the polygons.
We set the number of sides with the sides
.
fill
is the background of the polygon.
rotate
is the number of degrees to rotate it.
In the Example
component, we add the polygons onto the screen with the polygons.map
callback.
We add the Polygon
component with the props to set the sides, fill, and rotation angle.
Conclusion
We can add polygons into our React app with the Visx library.