Categories
Visx

Add a Mercator Map into Our React App with the Visx Library

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 a map view into our React app

Install Required Packages

We have to install a few modules to create the map.

To get started, we run:

npm i @visx/geo @visx/responsive @visx/scale

to install the packages.

Add the Map

We can add the map with the Mercator projection by writing:

import React from "react";
import { scaleQuantize } from "@visx/scale";
import { Mercator, Graticule } from "@visx/geo";
import * as topojson from "topojson-client";
import topology from "./world-topo.json";

const background = "#f9f7e8";
const world = topojson.feature(topology, topology.objects.units);

const color = scaleQuantize({
  domain: [
    Math.min(...world.features.map((f) => f.geometry.coordinates.length)),
    Math.max(...world.features.map((f) => f.geometry.coordinates.length))
  ],
  range: [
    "#ffb01d",
    "#ffa020",
    "#ff9221",
    "#ff8424",
    "#ff7425",
    "#fc5e2f",
    "#f94b3a",
    "#f63a48"
  ]
});

const Example = ({ width, height, events = false }) => {
  const centerX = width / 2;
  const centerY = height / 2;
  const scale = (width / 630) * 100;

  return width < 10 ? null : (
    <svg width={width} height={height}>
      <rect
        x={0}
        y={0}
        width={width}
        height={height}
        fill={background}
        rx={14}
      />
      <Mercator
        data={world.features}
        scale={scale}
        translate={[centerX, centerY + 50]}
      >
        {(mercator) => (
          <g>
            <Graticule
              graticule={(g) => mercator.path(g) || ""}
              stroke="rgba(33,33,33,0.05)"
            />
            {mercator.features.map(({ feature, path }, i) => (
              <path
                key={`map-feature-${i}`}
                d={path || ""}
                fill={color(feature.geometry.coordinates.length)}
                stroke={background}
                strokeWidth={0.5}
                onClick={() => {
                  if (events)
                    alert(
                      `Clicked: ${feature.properties.name} (${feature.id})`
                    );
                }}
              />
            ))}
          </g>
        )}
      </Mercator>
    </svg>
  );
};

export default function App() {
  return (
    <div className="App">
      <Example width={500} height={300} />
    </div>
  );
}

world-topo.json can be found at https://codesandbox.io/s/github/airbnb/visx/tree/master/packages/visx-demo/src/sandboxes/visx-geo-custom?file=/world-topo.json

We add the color variable to add the colors of the countries on the map.

Then in the Example component, we add the centerX and centerY variables to set the center of the map.

scale has the initial zoom level.

Then to add a 2D map that uses the Mercator projection, we add the Mercator component.

The data prop is set to the world variable, which created from the topojson.feature method with th topology JSON as the argument.

Then in its render prop, we add the Graticule component to add the map grid lines.

And the path element draws the countries.

Conclusion

We can add a simple 2D map easily into our React app with the Visx library.

Categories
Visx

Add Drag and Drop Features into Our React App with the Visx Library

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 curves with segments that have their own styles into our React app

Install Required Packages

We have to install a few modules.

To get started, we run:

npm i @visx/drag @visx/gradient @visx/responsive @visx/scale

to install the packages.

Add Drag and Drop Feature

We add drag and drop by writing the following code:

import React, { useMemo, useState, useEffect } from "react";
import { scaleOrdinal } from "@visx/scale";
import { LinearGradient } from "@visx/gradient";
import { Drag, raise } from "@visx/drag";

const colors = [
  "#025aac",
  "#02cff9",
  "#02efff",
  "#03aeed",
  "#0384d7",
  "#edfdff",
  "#ab31ff",
  "#5924d7"
];

const generateCircles = ({ width, height }) =>
  new Array(width < 360 ? 40 : 185).fill(1).map((d, i) => {
    const radius = 25 - Math.random() * 20;
    return {
      id: `${i}`,
      radius,
      x: Math.round(Math.random() * (width - radius * 2) + radius),
      y: Math.round(Math.random() * (height - radius * 2) + radius)
    };
  });

function Example({ width, height }) {
  const [draggingItems, setDraggingItems] = useState([]);

  useEffect(() => {
    if (width > 10 && height > 10)
      setDraggingItems(generateCircles({ width, height }));
  }, [width, height]);

  const colorScale = useMemo(
    () =>
      scaleOrdinal({
        range: colors,
        domain: draggingItems.map((d) => d.id)
      }),
    [width, height]
  );

  if (draggingItems.length === 0 || width < 10) return null;

  return (
    <div className="Drag" style={{ touchAction: "none" }}>
      <svg width={width} height={height}>
        <LinearGradient id="stroke" from="#ff00a5" to="#ffc500" />
        <rect fill="#c4c3cb" width={width} height={height} rx={14} />

{draggingItems.map((d, i) => (
          <Drag
            key={`drag-${d.id}`}
            width={width}
            height={height}
            x={d.x}
            y={d.y}
            onDragStart={() => {
              setDraggingItems(raise(draggingItems, i));
            }}
          >
            {({ dragStart, dragEnd, dragMove, isDragging, x, y, dx, dy }) => (
              <circle
                key={`dot-${d.id}`}
                cx={x}
                cy={y}
                r={isDragging ? d.radius + 4 : d.radius}
                fill={isDragging ? "url(#stroke)" : colorScale(d.id)}
                transform={`translate(${dx}, ${dy})`}
                fillOpacity={0.9}
                stroke={isDragging ? "white" : "transparent"}
                strokeWidth={2}
                onMouseMove={dragMove}
                onMouseUp={dragEnd}
                onMouseDown={dragStart}
                onTouchStart={dragStart}
                onTouchMove={dragMove}
                onTouchEnd={dragEnd}
              />
            )}
          </Drag>
        ))}
      </svg>
      <style jsx>{`
        .Drag {
          display: flex;
          flex-direction: column;
          user-select: none;
        }

        svg {
          margin: 1rem 0;
        }
        .deets {
          display: flex;
          flex-direction: row;
          font-size: 12px;
        }
        .deets > div {
          margin: 0.25rem;
        }
      `}</style>
    </div>
  );
}

export default function App() {
  return (
    <div className="App">
      <Example width={500} height={300} />
    </div>
  );
}

We have the generateCircles function to return an array of objects with id , radius , and x and y properties.

id is the unique ID for each circle.

And the other properties are used to render circles on the page.

In the Example component, we keep track of the items being tracked with the draggingItems state.

We watch the width and height and add the circles in the useEffect hook callback.

The colorScale state lets us compute the scale for the colors according to the colors array we created earlier.

In the return statement, we have the Drag component, which is the container for holding draggable items.

Then we render the draggable items with the render prop in the Drag component.

It renders the circles in the draggingItems array.

We pass in the drag event handlers from the object parameter as props of the circle to make them draggable.

Their positions will be updated with those event handler functions.

Finally, we have the styles in the style tag to change the styles for the container.

Now we should have circles on the screen that can be dragged around the box.

Conclusion

We can add drag and drop features into our React app with the Visx library.

Categories
Visx

Add Lines with Multiple Styles into a React App with the Visx Library

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 curves with segments that have their own styles into our React app

Install Required Packages

We have to install a few modules.

To get started, we run:

npm i @visx/curve @visx/gradient @visx/responsive @visx/scale @visx/shape

to install the packages.

Create the Multi-Styled Line

We can create the chart by adding the items provided by the modules.

To add the line, we write:

import React, { useMemo } from "react";
import { scaleLinear } from "@visx/scale";
import { curveCardinal } from "@visx/curve";
import { LinePath, SplitLinePath } from "@visx/shape";
import { LinearGradient } from "@visx/gradient";

const getX = (d) => d.x;
const getY = (d) => d.y;
const background = "#045275";
const backgroundLight = "#089099";
const foreground = "#b7e6a5";

function generateSinPoints({
  width,
  height,
  numberOfWaves = 10,
  pointsPerWave = 10
}) {
  const waveLength = width / numberOfWaves;
  const distanceBetweenPoints = waveLength / pointsPerWave;
  const sinPoints = [];

  for (let waveIndex = 0; waveIndex <= numberOfWaves; waveIndex += 1) {
    const waveDistFromStart = waveIndex * waveLength;

    for (let pointIndex = 0; pointIndex <= pointsPerWave; pointIndex += 1) {
      const waveXFraction = pointIndex / pointsPerWave;
      const waveX = pointIndex * distanceBetweenPoints;
      const globalX = waveDistFromStart + waveX;
      const globalXFraction = (width - globalX) / width;
      const waveHeight =
        Math.min(globalXFraction, 1 - globalXFraction) * height;
      sinPoints.push({
        x: globalX,
        y: waveHeight * Math.sin(waveXFraction * (2 * Math.PI))
      });
    }
  }

  return sinPoints;
}

function Example({
  width,
  height,
  numberOfWaves = 10,
  pointsPerWave = 100,
  numberOfSegments = 8
}) {
  const data = useMemo(
    () => generateSinPoints({ width, height, numberOfWaves, pointsPerWave }),
    [width, height, numberOfWaves, pointsPerWave]
  );

  const dividedData = useMemo(() => {
    const segmentLength = Math.floor(data.length / numberOfSegments);
    return new Array(numberOfSegments)
      .fill(null)
      .map((_, i) => data.slice(i * segmentLength, (i + 1) * segmentLength));
  }, [numberOfSegments, data]);

  const getScaledX = useMemo(() => {
    const xScale = scaleLinear({ range: [0, width], domain: [0, width] });
    return (d) => xScale(getX(d)) ?? 0;
  }, [width]);

  const getScaledY = useMemo(() => {
    const yScale = scaleLinear({ range: [0, height], domain: [height, 0] });
    return (d) => yScale(getY(d)) ?? 0;
  }, [height]);

  return width < 10 ? null : (
    <div>
      <svg width={width} height={height}>
        <LinearGradient
          id="visx-shape-splitlinepath-gradient"
          from={background}
          to={backgroundLight}
          fromOpacity={0.8}
          toOpacity={0.8}
        />
        <rect
          x={0}
          y={0}
          width={width}
          height={height}
          fill="url(#visx-shape-splitlinepath-gradient)"
          rx={14}
        />

        <g transform={`rotate(${0})translate(${-0}, ${-height * 0.5})`}>
          <LinePath
            data={data}
            x={getScaledX}
            y={getScaledY}
            strokeWidth={8}
            stroke="#fff"
            strokeOpacity={0.15}
            curve={curveCardinal}
          />

          <SplitLinePath
            segments={dividedData}
            x={getScaledX}
            y={getScaledY}
            curve={curveCardinal}
            styles={[
              { stroke: foreground, strokeWidth: 3 },
              { stroke: "#fff", strokeWidth: 2, strokeDasharray: "9,5" },
              { stroke: background, strokeWidth: 2 }
            ]}
          >
            {({ segment, styles, index }) =>
              index === numberOfSegments - 1 || index === 2 ? (
                segment.map(({ x, y }, i) =>
                  i % 8 === 0 ? (
                    <circle
                      key={i}
                      cx={x}
                      cy={y}
                      r={10 * (i / segment.length)}
                      stroke={styles?.stroke}
                      fill="transparent"
                      strokeWidth={1}
                    />
                  ) : null
                )
              ) : (
                <LinePath
                  data={segment}
                  x={(d) => d.x || 0}
                  y={(d) => d.y || 0}
                  {...styles}
                />
              )
            }
          </SplitLinePath>
        </g>
      </svg>
    </div>
  );
}

export default function App() {
  return (
    <div className="App">
      <Example width={500} height={300} />
    </div>
  );
}

We add the getX and getY functions to get the data for the x and y axes.

background is one of the colors of the background gradient.

backgroundLight has the lighter color of the background gradient.

foreground has one of the line colors.

We generate the points for the line with the generateSinPoints function.

globalX has the x coordinates for the sine curve.

And we use the Math.sin method to create the y axis value.

In the Example component, we render the line with various styles.

We divide the line into segments with the dividedData variable.

This is done by creating an array of values and slicing the values created from generateSinPoints with slice .

Then we create the scales for the graph with the getScaledX and getScaledY variables.

We create them with the scaleLinear function since everything is in linear scale.

Then we render the left line segment with the LinePath component.

And we use the SplitLinePath component to render the remaining segments.

We get the styles from the styles prop and render them styles with the LineSegment component we return in the render prop of SplitLinePath .

Conclusion

We can create a line with multiple segments with their own styles in our React app with the Visx library.

Categories
Visx

Add Marker Icons onto Lines with the Visx Library

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 a line with markers into our React app.

Install Required Packages

We have to install a few modules.

To get started, we run:

npm i @visx/curve @visx/glyph @visx/group @visx/mock-data @visx/responsive @visx/scale @visx/shape

to install the packages.

Create Lines with Markers

We can create lines with markers with the @visx/glyph module to add the markers.

To do this, we write:

import React from "react";
import { Group } from "@visx/group";
import {
  Glyph as CustomGlyph,
  GlyphCircle,
  GlyphCross,
  GlyphDiamond,
  GlyphSquare,
  GlyphStar,
  GlyphTriangle,
  GlyphWye
} from "@visx/glyph";
import { LinePath } from "@visx/shape";
import genDateValue from "@visx/mock-data/lib/generators/genDateValue";
import { scaleTime, scaleLinear } from "@visx/scale";
import { curveMonotoneX, curveBasis } from "@visx/curve";

const defaultMargin = { top: 10, right: 10, bottom: 10, left: 10 };

export const primaryColor = "#8921e0";
export const secondaryColor = "#00f2ff";
const contrastColor = "#ffffff";

const Glyphs = [
  GlyphCircle,
  GlyphCross,
  GlyphDiamond,
  GlyphStar,
  GlyphTriangle,
  GlyphSquare,
  GlyphWye,
  ({ left, top }) => (
    <CustomGlyph left={left} top={top}>
      <circle r={12} fill={secondaryColor} />
      <text fontSize={16} textAnchor="middle" dy="0.5em">
        {"?"}
      </text>
    </CustomGlyph>
  )
];

const data = genDateValue(Glyphs.length * 2);

const date = (d) => d.date.valueOf();
const value = (d) => d.value;

const xScale = scaleTime({
  domain: [Math.min(...data.map(date)), Math.max(...data.map(date))]
});
const yScale = scaleLinear({
  domain: [0, Math.max(...data.map(value))]
});

const getX = (d) => xScale(date(d)) ?? 0;
const getY = (d) => yScale(value(d)) ?? 0;

function Example({ width, height, margin = defaultMargin }) {
  if (width < 10) return null;
  const innerWidth = width - margin.left - margin.right;
  const innerHeight = height - margin.top - margin.bottom;
  xScale.range([0, innerWidth]);
  yScale.range([innerHeight, 0]);

return (
    <svg width={width} height={height}>
      <rect
        x={0}
        y={0}
        width={width}
        height={height}
        fill={secondaryColor}
        rx={14}
      />
      <Group left={margin.left} top={margin.top}>
        <LinePath
          data={data}
          x={getX}
          y={getY}
          stroke={primaryColor}
          strokeWidth={2}
          strokeDasharray="2,2"
          curve={curveBasis}
        />
        <LinePath
          data={data}
          x={getX}
          y={getY}
          stroke={primaryColor}
          strokeWidth={2}
          curve={curveMonotoneX}
        />
        {data.map((d, i) => {
          const CurrGlyph = Glyphs[i % Glyphs.length];
          const left = getX(d);
          const top = getY(d);
          return (
            <g key={`line-glyph-${i}`}>
              <CurrGlyph
                left={left}
                top={top}
                size={110}
                stroke={secondaryColor}
                strokeWidth={10}
              />
              <CurrGlyph
                left={left}
                top={top}
                size={110}
                fill={i % 2 === 0 ? primaryColor : contrastColor}
                stroke={i % 2 === 0 ? contrastColor : primaryColor}
                strokeWidth={2}
              />
            </g>
          );
        })}
      </Group>
    </svg>
  );
}

export default function App() {
  return (
    <div className="App">
      <Example width={500} height={300} />
    </div>
  );
}

We add the margins for the graph with the defaultMargin variable.

primaryColor , secondaryColor have the colors for the lines.

contrastColor have the background color for the markers.

The Glyphs array have the icons and a function that returns a custom component with the icon.

CustomGlyph takes the left and top properties to set its position.

data has the data for the line.

date and value are functions that return the value given the entry.

xScale has the scale for the x-axis.

And yScale has the scale for the y-axis.

The Example component is where we put the chart together.

We set the width and height of the chart with the innerWidth and innerHeight variables.

The Group component wraps around the parts of the chart.

LinePath has the lines for the graph.

We pass in the getX and getY functions to render the data as lines.

The first LinePath renders a dotted line.

And the 2nd one renders a solid line.

The markers are rendered with the data.map callback.

It returns the CurrGlyph components to render our marker.

We set the left and top props to set the position.

CurrGlyph is created from the Glyphs array by getting the icon to render by its index.

Now we should see 2 lines with markers for each.

Conclusion

We can create lines with markers easily in our React app with the Visx library.

Categories
Visx

Create a Simple React Whiteboard with the Visx Library

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 a simple whiteboard into our React app.

Install Required Packages

We have to install a few modules.

To get started, we run:

npm i @visx/curve @visx/drag @visx/gradient @visx/responsive @visx/shape

to install the packages.

Create the Whiteboard

We can create the whiteboard by adding the items provided by the modules.

To do this, we write:

import React, { useCallback, useState } from "react";
import { LinePath } from "@visx/shape";
import { useDrag } from "@visx/drag";
import { curveBasis } from "@visx/curve";
import { LinearGradient } from "@visx/gradient";

function Example({ data = [], width, height }) {
  const [lines, setLines] = useState(data);
  const onDragStart = useCallback(
    (currDrag) => {
      setLines((currLines) => [
        ...currLines,
        [{ x: currDrag.x, y: currDrag.y }]
      ]);
    },
    [setLines]
  );
  const onDragMove = useCallback(
    (currDrag) => {
      setLines((currLines) => {
        const nextLines = [...currLines];
        const newPoint = {
          x: currDrag.x + currDrag.dx,
          y: currDrag.y + currDrag.dy
        };
        const lastIndex = nextLines.length - 1;
        nextLines[lastIndex] = [...(nextLines[lastIndex] || []), newPoint];
        return nextLines;
      });
    },
    [setLines]
  );
  const {
    x = 0,
    y = 0,
    dx,
    dy,
    isDragging,
    dragStart,
    dragEnd,
    dragMove
  } = useDrag({
    onDragStart,
    onDragMove,
    resetOnStart: true
  });

  return width < 10 ? null : (
    <div className="DragII" style={{ touchAction: "none" }}>
      <svg width={width} height={height}>
        <LinearGradient id="stroke" from="#ff614e" to="#ffdc64" />
        <rect fill="#04002b" width={width} height={height} rx={14} />
        {lines.map((line, i) => (
          <LinePath
            key={`line-${i}`}
            fill="transparent"
            stroke="url(#stroke)"
            strokeWidth={3}
            data={line}
            curve={curveBasis}
            x={(d) => d.x}
            y={(d) => d.y}
          />
        ))}

        <g>
          {isDragging && (
            <rect
              width={width}
              height={height}
              onMouseMove={dragMove}
              onMouseUp={dragEnd}
              fill="transparent"
            />
          )}
          {isDragging && (
            <g>
              <rect
                fill="white"
                width={8}
                height={8}
                x={x + dx - 4}
                y={y + dy - 4}
                pointerEvents="none"
              />
              <circle
                cx={x}
                cy={y}
                r={4}
                fill="transparent"
                stroke="white"
                pointerEvents="none"
              />
            </g>
          )}
          <rect
            fill="transparent"
            width={width}
            height={height}
            onMouseDown={dragStart}
            onMouseUp={isDragging ? dragEnd : undefined}
            onMouseMove={isDragging ? dragMove : undefined}
            onTouchStart={dragStart}
            onTouchEnd={isDragging ? dragEnd : undefined}
            onTouchMove={isDragging ? dragMove : undefined}
          />
        </g>
      </svg>
      <style jsx>{`
        .DragII {
          display: flex;
          flex-direction: column;
          user-select: none;
        }

        svg {
          margin: 1rem 0;
          cursor: crosshair;
        }

        .deets {
          display: flex;
          flex-direction: row;
          font-size: 12px;
        }
        .deets > div {
          margin: 0.25rem;
        }
      `}</style>
    </div>
  );
}

export default function App() {
  return (
    <div className="App">
      <Example width={500} height={300} />
    </div>
  );
}

In the Example component, we have the whiteboard.

We have the lines state to keep track of the lines.

The lines array is set by the onDragStart function.

Whenever we start dragging the mouse, we add to the lines array.

The line starts at the x and y coordinates of the mouse.

The onDragMove event handler function lets us add the line according to the coordinates of the mouse.

We pass those 2 functions into the useDrag hook to let us draw lines when dragging.

In the return statement, we render the LinePath by calling map on the lines array.

data is passed into the line function to render the line.

When isDragging is true , which is when we’re dragging our mouse, then the circle is shown to render the marker.

rect draws a transparent rectangle as we’re dragging.

The style tag has the styles we want to set for the whiteboard.

Conclusion

We can create a simple whiteboard in our React app easily with the Visx library.