Export Code
Connected
Treemap.js
import React, { useRef, useEffect } from 'react';
import { hierarchy, treemap } from 'd3-hierarchy';
import { scaleOrdinal } from 'd3-scale';
import { select } from 'd3-selection';

export const Treemap = ({ data, width, height }) => {
// Here the size of each leave is given in the 'value' field in input data
// hierarchy constructs the hiearchiy and sum calculates the values along each layer
const root = hierarchy(data).sum((d) => d.value);

// Build tremap from root node
const tree = treemap()
.size([width, height])
.paddingTop(28)
.paddingRight(7)
.paddingInner(3)(root);

const colorScale = scaleOrdinal()
.domain(['boss1', 'boss2', 'boss3'])
.range(['#402D54
Alt + Click on a hex color
Open a color picker to modify the color
', '#D18975
Alt + Click on a hex color
Open a color picker to modify the color
', '#8FD175
Alt + Click on a hex color
Open a color picker to modify the color
']);

// Old school d3 code, wrapped in react hooks.
// Based on https://www.d3-graph-gallery.com/graph/treemap_custom.html
// This would be the "easy" way to convert it to react. THIS IS NOT IN USE
// (if we wanted to use this, the svg in return needed to have ref={ref})
const ref = useRef();
useEffect(() => {
const svgElement = select(ref.current);
svgElement
.selectAll('rect')
.data(root.leaves())
.join('rect')
.attr('x', (d) => d.x0)
.attr('y', (d) => d.y0)
.attr('width', (d) => d.x1 - d.x0)
.attr('height', (d) => d.y1 - d.y0)

Treemap Template in React

iblub

Last edited Oct 09, 2021
Created on Oct 09, 2021

This is a recreation of the Treemap Customization. It is rewritten to use React instead of only d3, if you come from the 2021 Data Visualization course, this template will be more understandable for you.

It also has an example using react hooks to "convert" the code.

MIT Licensed