Categories
React

Show and Hide Items with a React App with react-isotope

The react-isotope library lets us show and hide items by writing a few functions.

In this article, we’ll look at how to add filters for our items with React.

Install

We can install it by running:

npm install --save react-isotope

Adding Filters

We can add filters by adding the layout.

We add the cardsLayout.json to let us control how the items are filtered:

[
  {
    "id": "a",
    "row": 0,
    "col": 0,
    "w": 1,
    "h": 1,
    "filter": ["test", "chart"]
  },
  {
    "id": "b",
    "row": 0,
    "col": 1,
    "w": 1,
    "h": 1,
    "filter": ["test1", "tile"]
  },
  {
    "id": "c",
    "row": 0,
    "col": 3,
    "w": 1,
    "h": 1,
    "filter": ["test", "chart"]
  },
  {
    "id": "d",
    "row": 1,
    "col": 0,
    "w": 1,
    "h": 1,
    "filter": ["test1", "tile"]
  },
  {
    "id": "e",
    "row": 1,
    "col": 1,
    "w": 1,
    "h": 1,
    "filter": ["test", "tile"]
  },
  {
    "id": "f",
    "row": 1,
    "col": 2,
    "w": 1,
    "h": 1,
    "filter": ["test1", "chart"]
  },
  {
    "id": "h",
    "row": 2,
    "col": 0,
    "w": 1,
    "h": 1,
    "filter": ["test1", "chart"]
  }
]

Then in our React component, we write:

import React from "react";
import IsoTopeGrid from "react-isotope";
import cardsLayout from "./cardsLayout.json";

const filtersDefault = [
  { label: "all", isChecked: true },
  { label: "test", isChecked: false },
  { label: "test1", isChecked: false },
  { label: "chart", isChecked: false },
  { label: "tile", isChecked: false }
];
export default function App() {
  const [filters, updateFilters] = React.useState(filtersDefault);

const onFilter = (event) => {
    const {
      target: { value, checked }
    } = event;

updateFilters((state) =>
      state.map((f) => {
        if (f.label === value) {
          return {
            ...f,
            isChecked: checked
          };
        }

return f;
      })
    );
  };

return (
    <div className="App">
      <div className="filter-container">
        {filters.map((f) => (
          <div className="filter" key={`${f.label}_key`}>
            <input
              id={f.label}
              type="checkbox"
              value={f.label}
              onChange={onFilter}
              checked={f.isChecked}
            />
            <label htmlFor={f.label}>{f.label}</label>
          </div>
        ))}
      </div>
      <div className="container">
        <IsoTopeGrid
          gridLayout={cardsLayout}
          noOfCols={3}
          unitWidth={200}
          unitHeight={100}
          filters={filters}
        >
          {cardsLayout.map((card) => (
            <div key={card.id} className={card.filter[0]}>
              {card.id}
            </div>
          ))}
        </IsoTopeGrid>
      </div>
    </div>
  );
}

The IsoTopeGrid lets us display the filtered items in a grid.

Above that, we render the filter types into the checkboxes.

Once we check that filters, then the onFilter method to call the updateFilters method to set the callback to match the value.

We filter the value from the JSON by checking if the label is in the filter array.

Now when we click on the checkboxes, we show the items with the given labels.

The items will be animated as they’re updated.

Conclusion

We can add filters for items easily with the react-isotope library.

Categories
React

Recharts — Treemap and Custom Tooltip

We can add charts easily to a React app with Recharts.

In this article, we’ll look at how to use it.

Treemap

We can add a treemap with the Treemap component.

For instance, we can write:

import React from "react";
import { Treemap } from "recharts";

const data = [
  {
    name: "axis",
    children: [
      { name: "Axes", size: 1302 },
      { name: "Axis", size: 24593 }
    ]
  },
  {
    name: "controls",
    children: [
      { name: "AnchorControl", size: 2138 },
      { name: "ClickControl", size: 3824 }
    ]
  },
  {
    name: "data",
    children: [
      { name: "Data", size: 20544 },
      { name: "DataList", size: 19788 },
      {
        name: "render",
        children: [
          { name: "ArrowType", size: 698 },
          { name: "EdgeRenderer", size: 5569 }
        ]
      },
      { name: "ScaleBinding", size: 11275 },
      { name: "Tree", size: 7147 },
      { name: "TreeBuilder", size: 9930 }
    ]
  },
  {
    name: "operator",
    children: [
      {
        name: "distortion",
        children: [
          { name: "BifocalDistortion", size: 4461 },
          { name: "Distortion", size: 6314 }
        ]
      },
      { name: "IOperator", size: 1286 },
      { name: "Operator", size: 2490 },
      { name: "OperatorList", size: 5248 }
    ]
  }
];

export default function App() {
  return (
    <div className="App">
      <Treemap
        width={400}
        height={200}
        data={data}
        dataKey="size"
        ratio={4 / 3}
        stroke="#fff"
        fill="#8884d8"
      />
    </div>
  );
}

to add the data for the treemap and render it.

data has an array with objects that have the name and children properties.

The children objects have the size s we want to display.

width and height sets the dimensions of the treemap.

ratio has the aspect radio for the treemap.

stroke has the line color.

fill has the background color.

dataKey has the property name with the values we want to render.

Tooltip

We can customize tooltips to display the data we want.

For example, we can write:

import React from "react";
import {
  BarChart,
  Bar,
  XAxis,
  YAxis,
  CartesianGrid,
  Tooltip,
  Legend
} from "recharts";

const data = [
  {
    name: "Page A",
    uv: 4000,
    pv: 2400,
    amt: 2400
  },
  {
    name: "Page B",
    uv: 3000,
    pv: 1398,
    amt: 2210
  },
  {
    name: "Page C",
    uv: 2000,
    pv: 9800,
    amt: 2290
  }
];

const getIntroOfPage = (label) => {
  if (label === "Page A") {
    return "Page A is about men's clothing";
  }
  if (label === "Page B") {
    return "Page B is about women's dress";
  }
  if (label === "Page C") {
    return "Page C is about women's bag";
  }
};

const CustomTooltip = ({ active, payload, label }) => {
  if (active) {
    return (
      <div className="custom-tooltip">
        <p className="label">{`${label} : ${payload[0].value}`}</p>
        <p className="intro">{getIntroOfPage(label)}</p>
      </div>
    );
  }

  return null;
};

export default function App() {
  return (
    <div className="App">
      <BarChart
        width={500}
        height={300}
        data={data}
        margin={{
          top: 5,
          right: 30,
          left: 20,
          bottom: 5
        }}
      >
        <CartesianGrid strokeDasharray="3 3" />
        <XAxis dataKey="name" />
        <YAxis />
        <Tooltip content={<CustomTooltip />} />
        <Legend />
        <Bar dataKey="pv" barSize={20} fill="#8884d8" />
      </BarChart>
    </div>
  );
}

We have the CustomTooltip component to render the tooltip the way we want.

We pass that into the content prop so that we can render what we want.

Conclusion

We can add a treemap and customize labels with the Recharts.

Categories
React

Recharts — Scatter and Pie Charts

We can add charts easily to a React app with Recharts.

In this article, we’ll look at how to use it.

Scatter Chart

We can add a scatter chart with the ScatterChart component.

For example, we can write:

import React from "react";
import {
  ScatterChart,
  Scatter,
  XAxis,
  YAxis,
  CartesianGrid,
  Tooltip
} from "recharts";

const data = [
  { x: 100, y: 200, z: 200 },
  { x: 120, y: 100, z: 260 },
  { x: 170, y: 300, z: 400 }
];

export default function App() {
  return (
    <div className="App">
      <ScatterChart
        width={400}
        height={400}
        margin={{
          top: 20,
          right: 20,
          bottom: 20,
          left: 20
        }}
      >
        <CartesianGrid />
        <XAxis type="number" dataKey="x" name="stature" unit="cm" />
        <YAxis type="number" dataKey="y" name="weight" unit="kg" />
        <Tooltip cursor={{ strokeDasharray: "3 3" }} />
        <Scatter name="A school" data={data} fill="#8884d8" />
      </ScatterChart>
    </div>
  );
}

We nest the components of our chart inside the ScatterChart component.

width and height has the dimensions.

margin has the margins of the chart.

CartesianGrid has the grid in the background.

XAxis has the x-axis with the labels.

type sets the type of the x-axis.

dataKey has the property name with the values we want to display as labels.

unit has the unit we want to display at the end of the label.

Tooltip has the tooltip.

Scatter has the dots we want to display.

data has the x and y coordinates of the dots.

fill has the dot’s color.

Pie Chart

We can add a pie chart with the PieChart component.

For example, we can write:

import React from "react";
import { PieChart, Pie, Tooltip } from "recharts";

const data = [
  { name: "Group A", value: 400 },
  { name: "Group B", value: 300 },
  { name: "Group C", value: 300 }
];
export default function App() {
  return (
    <div className="App">
      <PieChart width={400} height={400}>
        <Pie
          dataKey="value"
          isAnimationActive={false}
          data={data}
          cx={200}
          cy={200}
          outerRadius={80}
          fill="#8884d8"
          label
        />
        <Tooltip />
      </PieChart>
    </div>
  );
}

to add our pie chart.

The Pie component defines the slices.

data has the data.

dataKey is the property name with the value for the slices.

label adds the labels.

fill has the fill color for the slices.

cx and cy circle’s length and width.

We can add a pie chart with 2 levels:

For example, we can write:

import React from "react";
import { PieChart, Pie, Tooltip } from "recharts";

const data = [
  { name: "Group A", value: 400 },
  { name: "Group B", value: 300 },
  { name: "Group C", value: 300 }
];

const data2 = [
  { name: "A1", value: 100 },
  { name: "A2", value: 300 },
  { name: "B1", value: 100 }
];
export default function App() {
  return (
    <div className="App">
      <PieChart width={400} height={400}>
        <Pie
          data={data}
          dataKey="value"
          cx={200}
          cy={200}
          outerRadius={60}
          fill="#8884d8"
        />
        <Pie
          data={data2}
          dataKey="value"
          cx={200}
          cy={200}
          innerRadius={70}
          outerRadius={90}
          fill="#82ca9d"
          label
        />
      </PieChart>
    </div>
  );
}

We set the outerRadius to the radius of the circle.

innerRadius and outerRadius together makes it a ring.

outerRadius is subtracted by the innerRadius .

Conclusion

We can add pie charts and scatter charts easily with Recharts.

Categories
React

Recharts — Radar and Radial Bar Charts

We can add charts easily to a React app with Recharts.

In this article, we’ll look at how to use it.

Radar Chart

We can add a radar chart with the Radar and RadarChart components.

For example, we can write:

import React from "react";
import {
  Radar,
  RadarChart,
  PolarGrid,
  PolarAngleAxis,
  PolarRadiusAxis
} from "recharts";

const data = [
  {
    subject: "Math",
    A: 120,
    B: 110,
    fullMark: 150
  },
  {
    subject: "Science",
    A: 98,
    B: 130,
    fullMark: 150
  },
  {
    subject: "English",
    A: 86,
    B: 130,
    fullMark: 150
  }
];
export default function App() {
  return (
    <div className="App">
      <RadarChart
        cx={300}
        cy={250}
        outerRadius={150}
        width={500}
        height={500}
        data={data}
      >
        <PolarGrid />
        <PolarAngleAxis dataKey="subject" />
        <PolarRadiusAxis />
        <Radar
          name="Mike"
          dataKey="A"
          stroke="#8884d8"
          fill="#8884d8"
          fillOpacity={0.6}
        />
      </RadarChart>
    </div>
  );
}

We add the RadarChart component to wrap around the points.

outerRadius has the radius of the radar chart.

width and height has the dimensions.

PolarGrid adds the grid lines.

PolarAngleAxis sets the axis.

The dataKey prop is set to the property name of the key.

PolarRadiusAxis has the axes with the numbers.

Radar has the radar chart values.

dataKey has the property name with the values for the radar chart.

fill has the fill color.

stroke has the stroke color for the radar chart.

fillOpacity sets the opacity for the fill of the shape connected by the dots.

Radial Bar Chart

Recharts lets us add radial bar charts.

For example, we can write:

import React from "react";
import { RadialBarChart, RadialBar, Legend } from "recharts";

const data = [
  {
    name: "18-24",
    uv: 31,
    pv: 2400,
    fill: "#8884d8"
  },
  {
    name: "25-29",
    uv: 26,
    pv: 4567,
    fill: "#83a6ed"
  },
  {
    name: "30-34",
    uv: 17,
    pv: 1398,
    fill: "#8dd1e1"
  }
];

const style = {
  top: 0,
  left: 350,
  lineHeight: "24px"
};

export default function App() {
  return (
    <div className="App">
      <RadialBarChart
        width={500}
        height={300}
        cx={150}
        cy={150}
        innerRadius={20}
        outerRadius={140}
        barSize={10}
        data={data}
      >
        <RadialBar
          minAngle={15}
          label={{ position: "insideStart", fill: "#fff" }}
          background
          clockWise
          dataKey="uv"
        />
        <Legend
          iconSize={10}
          width={120}
          height={140}
          layout="vertical"
          verticalAlign="middle"
          wrapperStyle={style}
        />
      </RadialBarChart>
    </div>
  );
}

The RadialBarChart has the bars.

width and height has the dimensions of the radial bar chart.

innerRadius and outerRadius defines the radii for the innermost and outermost rings.

data has the data we want to display.

RadialBar has the radial bars to display.

clockwise makes it animate clockwise.

dataKey has the property name with the value for the bars.

background makes a background color display.

Legend has the legend for the bars.

layout sets the layout for the legend.

verticalAlign sets the vertical alignment.

wrapperStyle has the style for the legend’s wrapper element.

iconSize sets the size of the icons.

width and height sets the dimensions of the legend.

Conclusion

We can add radar and radial bar charts with Recharts.

Categories
React

Recharts — Change Opacity of Line When Hovering Over Legend and Responsive Container

We can add charts easily to a React app with Recharts.

In this article, we’ll look at how to use it.

Change Opacity of Line When Hovering Over Legend

We can change the opacity of the line when we hover over the legend.

For example, we can write:

import React from "react";
import {
  LineChart,
  Line,
  XAxis,
  YAxis,
  CartesianGrid,
  Tooltip,
  Legend
} from "recharts";

const data = [
  {
    name: "Page A",
    uv: 4000,
    pv: 2400,
    amt: 2400
  },
  {
    name: "Page B",
    uv: 3000,
    pv: 1398,
    amt: 2210
  },
  {
    name: "Page C",
    uv: 2000,
    pv: 9800,
    amt: 2290
  }
];

export default function App() {
  const [opacity, setOpacity] = React.useState({
    uv: 1,
    pv: 1
  });

  const handleMouseEnter = (o) => {
    const { dataKey } = o;
    setOpacity({ ...opacity, [dataKey]: 0.5 });
  };

  const handleMouseLeave = (o) => {
    const { dataKey } = o;
    setOpacity({ ...opacity, [dataKey]: 1 });
  };

  return (
    <div className="App">
      <LineChart
        width={500}
        height={300}
        data={data}
        margin={{
          top: 5,
          right: 30,
          left: 20,
          bottom: 5
        }}
      >
        <CartesianGrid strokeDasharray="3 3" />
        <XAxis dataKey="name" />
        <YAxis />
        <Tooltip />
        <Legend
          onMouseEnter={handleMouseEnter}
          onMouseLeave={handleMouseLeave}
        />
        <Line
          type="monotone"
          dataKey="pv"
          strokeOpacity={opacity.pv}
          stroke="#8884d8"
          activeDot={{ r: 8 }}
        />
        <Line
          type="monotone"
          dataKey="uv"
          strokeOpacity={opacity.uv}
          stroke="#82ca9d"
        />
      </LineChart>
    </div>
  );
}

We have the opacity state to set the opacity of the line.

The Legend has the onMouseEnter and onMouseLeave props to set the functions to set the opacity of the lines when we hover the lines.

The strokeOpacity prop of the Line component sets the opacity of the line.

Responsive Container

We can add a responsive container for our charts with the ResponsiveContainer component.

For example, we can write:

import React from "react";
import {
  AreaChart,
  Area,
  XAxis,
  YAxis,
  CartesianGrid,
  Tooltip,
  ResponsiveContainer
} from "recharts";

const data = [
  {
    name: "Page A",
    uv: 4000,
    pv: 2400,
    amt: 2400
  },
  {
    name: "Page B",
    uv: 3000,
    pv: 1398,
    amt: 2210
  },
  {
    name: "Page C",
    uv: 2000,
    pv: 9800,
    amt: 2290
  }
];
export default function App() {
  return (
    <div className="App" style={{ width: "100%", height: 300 }}>
      <ResponsiveContainer>
        <AreaChart
          data={data}
          margin={{
            top: 10,
            right: 30,
            left: 0,
            bottom: 0
          }}
        >
          <CartesianGrid strokeDasharray="3 3" />
          <XAxis dataKey="name" />
          <YAxis />
          <Tooltip />
          <Area type="monotone" dataKey="uv" stroke="#8884d8" fill="#8884d8" />
        </AreaChart>
      </ResponsiveContainer>
    </div>
  );
}

to add the charts.

We set the width and height of the div.

And the ResponsiveContainer will fill the width and height of the div.

Conclusion

We can change the line opacity when we hover over the legend and the responsive container with Recharts.