VISX library in ReactJS - GeeksforGeeks

14 Jan, 2021
VISX is a library that allows us to add designs to our React app without any problem. In the following example, we have shown how to utilize it to add territory contrast graphs into our React app.
Module Installation: We’ve to install numerous modules given by the Visx library to make the Area Difference Chart. To do so, run the following command from your terminal.
$ npm install --save @visx/axis @visx/curve 
@visx/gradient @visx/grid @visx/group @visx/mock-data 
@visx/react-spring @visx/responsive @visx/shape 
@visx/scale react-spring
Note: The @visx/mock-data library has mock data we can use in our visual charts.
Creating React Application:
Step 1: Create a React application using the following command:
npx create-react-app foldername
Step 2: After creating your project folder i.e. foldername, move to it using the following command:
cd foldername
Project Structure: It will look like the following.
Project Structure
Example: To add the filled line graph, we write the following code.
Filename: App.js
Javascript
import React, { useState, useMemo } from "react";import AreaClosed from "@visx/shape/lib/shapes/AreaClosed";import { curveMonotoneX } from "@visx/curve";import {  scaleUtc,  scaleLinear,  scaleLog,  scaleBand,  coerceNumber} from "@visx/scale";import { Orientation } from "@visx/axis";import {  AnimatedAxis,  AnimatedGridRows,  AnimatedGridColumns} from "@visx/react-spring";import { LinearGradient } from "@visx/gradient";import { timeFormat } from "d3-time-format";  export const backgroundColor = "#da7cff";const axisColor = "#fff";const tickLabelColor = "#fff";export const labelColor = "#340098";const gridColor = "#6e0fca";const margin = {  top: 40,  right: 150,  bottom: 20,  left: 50};  const tickLabelProps = () => ({  fill: tickLabelColor,  fontSize: 12,  fontFamily: "sans-serif",  textAnchor: "middle"});  const getMinMax = (vals) => {  const numericVals = vals.map(coerceNumber);  return [Math.min(...numericVals),          Math.max(...numericVals)];};  function Example({  width: outerWidth = 800,  height: outerHeight = 800,  showControls = true}) {  const width = outerWidth - margin.left - margin.right;  const height = outerHeight - margin.top - margin.bottom;  const [dataToggle] = useState(true);  const [animationTrajectory] = useState("center");    const axes = useMemo(() => {    const linearValues = dataToggle ? [0, 2, 4, 6, 8, 10] :                                      [6, 8, 10, 12];    return [      {        scale: scaleLinear({          domain: getMinMax(linearValues),          range: [0, width]        }),        values: linearValues,        tickFormat: (v, index, ticks) =>          index === 0            ? "first"            : index === ticks[ticks.length - 1].index            ? "last"            : `${v}`,        label: "linear"      }    ];  }, [dataToggle, width]);    if (width < 10) return null;    const scalePadding = 40;  const scaleHeight = height / axes.length - scalePadding;    const yScale = scaleLinear({    domain: [100, 0],    range: [scaleHeight, 0]  });    return (    <>      <svg width={outerWidth} height={outerHeight}>        <LinearGradient          id="visx-axis-gradient"          from={backgroundColor}          to={backgroundColor}          toOpacity={0.5}        />        <rect          x={0}          y={0}          width={outerWidth}          height={outerHeight}          fill={"url(#visx-axis-gradient)"}          rx={14}        />        <g transform={`translate(${margin.left},${margin.top})`}>          {axes.map(({ scale, values, label, tickFormat }, i) => (            <g              key={`scale-${i}`}              transform={`translate(0, ${i * (scaleHeight + scalePadding)})`}            >              <AnimatedGridRows                key={`gridrows-${animationTrajectory}`}                scale={yScale}                stroke={gridColor}                width={width}                numTicks={dataToggle ? 1 : 3}                animationTrajectory={animationTrajectory}              />              <AnimatedGridColumns                key={`gridcolumns-${animationTrajectory}`}                scale={scale}                stroke={gridColor}                height={scaleHeight}                numTicks={dataToggle ? 5 : 2}                animationTrajectory={animationTrajectory}              />              <AreaClosed                data={values.map((x) => [                  (scale(x) ?? 0) +                    ("bandwidth" in scale &&                    typeof scale.bandwidth !== "undefined"                      ? scale.bandwidth() / 2                      : 0),                  yScale(10 + Math.random() * 90)                ])}                yScale={yScale}                curve={curveMonotoneX}                fill={gridColor}                fillOpacity={0.2}              />              <AnimatedAxis                key={`axis-${animationTrajectory}`}                orientation={Orientation.bottom}                top={scaleHeight}                scale={scale}                tickFormat={tickFormat}                stroke={axisColor}                tickStroke={axisColor}                tickLabelProps={tickLabelProps}                tickValues={                  label === "log" || label === "time" ? undefined : values                }                numTicks={label === "time" ? 6 : undefined}                label={label}                labelProps={{                  x: width + 30,                  y: -10,                  fill: labelColor,                  fontSize: 18,                  strokeWidth: 0,                  stroke: "#fff",                  paintOrder: "stroke",                  fontFamily: "sans-serif",                  textAnchor: "start"                }}                animationTrajectory={animationTrajectory}              />            </g>          ))}        </g>      </svg>    </>  );}  export default function App() {  return (    <div>      <Example width="500" height="300" />    </div>  );}
Explanation: We add the backgroundColor to set the foundation tone, axisColor has the pivot tone, tickLabelColor has the x-hub tick name’s tone, labelColor has the y-hub name tone, gridColor has the network tone.  
We change the content styles with the tickLabelProps work.  To add the chart content, we add the axes cluster. We register the qualities for the diagram from the dataToggle object, linearValues has the straight scale esteem. We have the y-Scale object to add the y-pivot esteems. In the JSX we return, we add the SVG, rect square shape component, and afterward in the axes.map callback, we return the chart. The chart has the g-component with the SVG gathering, AnimatedGridRows has the enlivened lattice columns. 
We pass in the y-Scale incentive to it to show the y-esteems, stroke sets the stroke, width sets the width, AnimatedGridColumns has the framework sections, numTicks allows us to set the number of ticks on the x-hub. We have comparable code with the AnimatedGridColumns segment to add the sections, AreaClosed has the filled line chart, AnimatedAxis has the enlivened x-pivot. We set the name styles with the labelProps and tickValues has the tick esteems.
Step to Run Application: Run the application using the following command from the root directory of the project:
npm start
Output:
Technical Scripter 2020
ReactJS
Technical Scripter
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
How to set background images in ReactJS ?
How to create a table in ReactJS ?
How to navigate on path by button click in react router ?
How to create a multi-page website using React.js ?
ReactJS useNavigate() Hook
How to build a basic CRUD app with Node.js and ReactJS ?
Axios in React: A Guide for Beginners
How to parse JSON Data into React Table Component ?
Changing CSS styling with React onClick() Event
How to check the version of ReactJS ?