
Syncfusion React Treemaps
- 383 installs
- 3 repo stars
- Updated July 28, 2026
- syncfusion/react-ui-components-skills
Use syncfusion-react-treemaps for development tasks
About
syncfusion-react-treemaps: A skill for development. This provides functionality for development workflows.
- syncfusion-react-treemaps
Syncfusion React Treemaps by the numbers
- 383 all-time installs (skills.sh)
- +53 installs in the week ending Aug 5, 2026 (Skillselion tracking)
- Ranked #1,134 of 4,347 Backend & APIs skills by installs in the Skillselion catalog
- Data as of Aug 5, 2026 (Skillselion catalog sync)
npx skills add https://github.com/syncfusion/react-ui-components-skills --skill syncfusion-react-treemapsAdd your badge
Show developers this skill is listed on Skillselion. Paste this into your README.
| Installs | 383 |
|---|---|
| repo stars | ★ 3 |
| Last updated | July 28, 2026 |
| Repository | syncfusion/react-ui-components-skills ↗ |
What it does
Use syncfusion-react-treemaps for development tasks
Files
Implementing Syncfusion React TreeMap
A comprehensive guide for implementing and customizing the Syncfusion React TreeMap component for hierarchical data visualization. The TreeMap displays nested rectangles where area represents data values, supporting multiple hierarchy levels, interactive drill-down, and rich customization.
When to Use This Skill
Use this skill when you need to:
- Install and set up the TreeMap component
- Bind hierarchical or flat data to TreeMap
- Visualize tree-structured data with multiple levels
- Implement drill-down interactions for data exploration
- Apply color mapping strategies (range, equal, desaturation)
- Configure layouts (square, horizontal, vertical, auto)
- Add legends, tooltips, and data labels
- Implement selection and highlight features
- Customize leaf items and label positioning
- Handle accessibility requirements
- Export or print TreeMap visualizations
- Internationalize or apply RTL support
Component Overview
The TreeMap component is a powerful hierarchical data visualization tool that:
- Renders nested rectangles using SVG for scalability
- Supports any number of hierarchy levels
- Provides four layout algorithms for optimal space utilization
- Enables drill-down for exploring nested data
- Offers three color mapping types for data-driven styling
- Includes interactive features: selection, highlight, tooltips
- Supports data labels, legends, and custom templates
- Provides accessibility and internationalization support
When to Choose TreeMap
Choose TreeMap when:
- Visualizing hierarchical data (organizational charts, file systems, category hierarchies)
- Comparing multiple values across categories using area encoding
- Exploring nested categories through drill-down interaction
- Displaying tree-structured data with many items at multiple levels
- Need space-efficient visualization that uses area encoding
Don't use TreeMap for:
- Simple flat data with few items (use Bar/Column charts)
- Time-series data (use Line/Area charts)
- Relationships between entities (use Diagram/Graph)
- Single hierarchy with few nodes (consider alternative layouts)
Documentation and Navigation Guide
Getting Started
📄 Read: references/getting-started.md
- Installing @syncfusion/ej2-react-treemap
- Package dependencies and setup
- Module injection for features
- Creating your first TreeMap
- Rendering basic hierarchical data
Data Binding & Hierarchies
📄 Read: references/data-binding.md
- Flat vs hierarchical data structures
- Configuring weightValuePath for sizing
- Binding multilevel hierarchies with levels
- Remote data source integration
- Data transformation patterns
Color Mapping Strategies
📄 Read: references/color-mapping.md
- Range-based color mapping (gradient by values)
- Equal value color mapping (categorical colors)
- Desaturation mapping (opacity-based variation)
- Dynamic color assignment
- Choosing color mapping strategies
Layouts and Layout Selection
📄 Read: references/layouts.md
- Square layout (balanced aspect ratio)
- Horizontal layout (left-to-right ordering)
- Vertical layout (top-to-bottom ordering)
- Auto layout (default optimal layout)
- When to use each layout type
Drill-Down and Navigation
📄 Read: references/drilldown.md
- Enabling drill-down with enableDrillDown
- Configuring levels for multi-level exploration
- Drill-down events and callbacks
- Breadcrumb navigation patterns
- Back navigation handling
Leaf Items, Labels & Templates
📄 Read: references/leaf-items-and-labels.md
- Leaf item configuration and styling
- Label positioning (TopLeft, Center, BottomRight, etc.)
- Data label formatting and templates
- Border and fill customization
- Label overflow handling
Legends, Tooltips & Selection
📄 Read: references/legends-tooltips-selection.md
- Creating and configuring legends
- Tooltip templates and styling
- Selection and highlight modes
- Interactive features and events
- Responding to user interactions
Customization, Accessibility & Export
📄 Read: references/customization-accessibility.md
- WCAG compliance and keyboard navigation
- RTL (right-to-left) support
- Internationalization and localization
- Theming and CSS customization
- Print and export functionality
Quick Start Example
import * as React from 'react';
import { TreeMapComponent } from '@syncfusion/ej2-react-treemap';
export function TreeMapDemo() {
const data = [
{ Title: 'USA', State: 'California', Sales: 2830 },
{ Title: 'USA', State: 'Texas', Sales: 2020 },
{ Title: 'USA', State: 'Florida', Sales: 1880 },
{ Title: 'Germany', State: 'Berlin', Sales: 1880 },
{ Title: 'Germany', State: 'Munich', Sales: 1550 },
];
return (
<TreeMapComponent
height="350px"
dataSource={data}
weightValuePath="Sales"
leafItemSettings={{
labelPath: 'State',
colorMapping: [
{ from: 1500, to: 2000, color: '#FF6B6B' },
{ from: 2000, to: 2500, color: '#4ECDC4' },
{ from: 2500, to: 3000, color: '#45B7D1' }
]
}}
/>
);
}Common Patterns
Pattern 1: Hierarchical Data with Drill-Down
<TreeMapComponent
enableDrillDown={true}
dataSource={data}
weightValuePath="Sales"
>
<LevelsDirective>
<LevelDirective groupPath="Country" />
<LevelDirective groupPath="State" />
<LevelDirective groupPath="City" />
</LevelsDirective>
</TreeMapComponent>When to use: Exploring multilevel hierarchies with progressive disclosure through drill-down interaction.
Pattern 2: Color-Coded Categories
<TreeMapComponent
equalColorValuePath="Category"
leafItemSettings={{
colorMapping: [
{ value: 'Electronics', color: '#3498db' },
{ value: 'Furniture', color: '#e74c3c' },
{ value: 'Clothing', color: '#2ecc71' }
]
}}
/>When to use: Categorizing items with distinct colors for quick visual identification.
Pattern 3: Value-Range Color Gradient
<TreeMapComponent
rangeColorValuePath="Sales"
leafItemSettings={{
colorMapping: [
{ from: 0, to: 10000, color: '#90EE90' },
{ from: 10000, to: 50000, color: '#FFD700' },
{ from: 50000, to: 100000, color: '#FF6347' }
]
}}
/>When to use: Showing magnitude differences through color intensity for performance metrics, sales, or other continuous values.
Key Props and Configuration
| Prop | Purpose | Common Values |
|---|---|---|
dataSource | Hierarchical or flat data array | Array of objects |
weightValuePath | Property path for item sizing | e.g., 'Sales', 'Count' |
equalColorValuePath | Property for categorical coloring | e.g., 'Category', 'Type' |
rangeColorValuePath | Property for range-based coloring | e.g., 'Sales', 'Value' |
enableDrillDown | Enable click-to-drill interaction | true/false |
layoutType | Spatial layout algorithm | 'Squarified', 'Horizontal', 'Vertical', 'SliceAndDice' |
height | Component height | e.g., '350px', '100%' |
palette | Array of colors for items | ['#color1', '#color2', ...] |
Common Use Cases
API Reference
This section summarizes the most commonly used TreeMap props, methods, and events. For the complete API with typed models, see the official docs: https://ej2.syncfusion.com/react/documentation/api/treemap/index-default
Important Properties (selected)
dataSource(Array|DataManager) — The data source for TreeMap. Can be flat or hierarchical. Default:nullweightValuePath(string) — Path to numeric value used for sizing each item. Default:nullcolorValuePath(string) — Field used for continuous color mapping (range palettes).equalColorValuePath(string[]) — Field(s) for categorical/equal color mapping.rangeColorValuePath(string[]) — Field(s) used for range-based color mapping.leafItemSettings(object) — Configuration for leaf items (e.g.,labelPath,colorMapping,border,gap).levels(LevelSettingsModel[]) — Array of level configuration objects to define grouping and appearance per hierarchy level.layoutType(string) — Layout algorithm:Squarified(default),SliceAndDiceHorizontal,SliceAndDiceVertical,SliceAndDiceAuto, etc.enableDrillDown(boolean) — Enable drill-down interaction. Default:falsedrillDownView(boolean) — Use drill-down view layout. Default:falseenableBreadcrumb(boolean) — Show breadcrumb when drilling. Default:falsebreadcrumbConnector(string) — Separator shown between breadcrumb items.initialDrillDown(object) — Configure initial drill-down level/state.enableHtmlSanitizer(boolean) — Sanitize HTML in templates/tooltips. Default:trueenablePersistence(boolean) — Persist component state between reloads. Default:falseenableRtl(boolean) — Enable right-to-left rendering. Default:falsepalette(string[]) — Array of palette colors used for fills.highlightSettings(object) — Highlight configuration and styling.selectionSettings(object) — Selection configuration (mode, enable, etc.).legendSettings(object) — Legend configuration (position, title, shape, etc.).titleSettings(object) — Title and subtitle configuration.tooltipSettings(object) — Tooltip templates and behavior.format(string) — Formatting string for labels or values.useGroupingSeparator(boolean) — Apply grouping separator for numeric values. Default:truedescription(string) — Accessibility description for the TreeMap.margin(object) — Margin settings for the component ({ top, right, bottom, left }).height/width(string|number) — Size of the component (e.g.,350pxor100%).theme(string) — Theme name (e.g.,Material,Bootstrap).
Common Methods
destroy()— Clean up the TreeMap instance and remove listeners.export(type, fileName, orientation, allowDownload)— Export the TreeMap asPNG|JPEG|SVG|PDF. Returns a Promise for PDF export flows.print(id)— Print TreeMap content by element id, DOM element, or array of ids.doubleClickOnTreeMap(e)— Programmatically trigger double-click behavior.selectItem(levelOrder, isSelected)— Select or deselect an item by level order array.
Common Events
load/loaded— Lifecycle events fired before/after component load.itemRendering— Fired while items are rendered; use to customize item appearance.click/itemClick— Fired on item click.doubleClick— Fired on item double click.drillStart/drillEnd— Fired when drill-down starts/ends.itemHighlight/itemSelected— Events for highlight/selection lifecycle.legendRendering/legendItemRendering— Events during legend rendering.tooltipRendering— Fired when tooltip content is prepared.resize— Fired on component resize.beforePrint/print— Hooks around printing/export.
Quick Import Example
import { TreeMapComponent, LevelsDirective, LevelDirective, Inject, TreeMapTooltip } from '@syncfusion/ej2-react-treemap';
<TreeMapComponent dataSource={data} weightValuePath="value" enableDrillDown={true}>
<LevelsDirective>
<LevelDirective groupPath="category" />
</LevelsDirective>
<Inject services={[TreeMapTooltip]} />
</TreeMapComponent>1. Organization Hierarchies: Visualize employee counts across departments, regions, and divisions 2. File System Browser: Display disk usage by folders and subfolders with drill-down 3. Sales Performance: Compare regional sales, product categories, and territories 4. Website Analytics: Explore traffic sources, pages, and user segments hierarchically 5. Portfolio Allocation: Visualize asset distribution across categories and subcategories 6. Market Share: Display competitive landscape with company hierarchies 7. Budget Analysis: Allocate and visualize budget across departments and line items
Next Steps
1. Start with Getting Started guide to install and render your first TreeMap 2. Choose a data binding pattern based on your data structure 3. Select color mapping strategy (range, equal, or desaturation) 4. Configure layout and drill-down if exploring hierarchies 5. Customize leaf items, labels, and tooltips for your use case 6. Add interactivity with selection and events 7. Ensure accessibility and internationalization requirements
---
Ready to implement TreeMap? Start with references/getting-started.md or choose a specific feature guide from the navigation options above.
````markdown
TreeMap API Quick Reference
This reference summarizes the main properties, methods, and events of the Syncfusion React TreeMap component. For the full API and exact type definitions, see: https://ej2.syncfusion.com/react/documentation/api/treemap/index-default
Properties (high-level)
allowImageExport(boolean) — Enable exporting the TreeMap as an image. Default:falseallowPdfExport(boolean) — Enable exporting the TreeMap as PDF. Default:falseallowPrint(boolean) — Enable printing via theprintAPI. Default:falsebackground(string) — Background color of the TreeMap container.border(object) — Global border settings for the component (e.g.,{ color: string, width: number }).breadcrumbConnector(string) — Separator shown between breadcrumb items whenenableBreadcrumbis true.colorValuePath(string) — Data field used for color mapping (continuous palettes).dataSource(Array|DataManager) — The data source for TreeMap (flat array or hierarchical structure).description(string) — Description text used for accessibility.drillDownView(boolean) — Use drill-down view layout whenenableDrillDownis enabled. Default:falseenableBreadcrumb(boolean) — Show breadcrumb navigation for drill-down. Default:falseenableDrillDown(boolean) — Enable click-to-drill down interactions. Default:falseenableHtmlSanitizer(boolean) — Sanitize HTML in templates/tooltips to avoid XSS. Default:trueenablePersistence(boolean) — Persist component state between page reloads. Default:falseenableRtl(boolean) — Enable right-to-left rendering. Default:falseequalColorValuePath(string[]) — Field(s) to use for categorical/equal color mapping.format(string) — Format string for labels or values.height(string|number) — Height of the TreeMap (e.g.,350pxor100%).highlightSettings(object) — Settings for highlight behavior and styling.initialDrillDown(object) — Configuration for initial drill-down state.layoutType(string) — Layout algorithm:Squarified(default),SliceAndDiceHorizontal,SliceAndDiceVertical,SliceAndDiceAuto, etc.leafItemSettings(object) — Configuration for leaf items (e.g.,labelPath,border,colorMapping,gap,showLabels).legendSettings(object) — Legend configuration (position, size, title, etc.).levels(array) — Array of level configuration objects for grouped hierarchies (LevelSettingsModel[]).locale(string) — Current locale used for formatting and messages.margin(object) — Margin settings for the TreeMap ({ top, right, bottom, left }).palette(string[]) — Array of colors used for filling items when color mapping is not explicit.query(Query) — ExternalQuery(DataManager) used for remote data operations.rangeColorValuePath(string[]) — Field(s) used for range color mapping.renderDirection(string) — Rendering direction (e.g.,TopLeftBottomRight).selectionSettings(object) — Selection-related settings (mode, enable, etc.).tabIndex(number) — Tab index for keyboard navigation. Default:0theme(string) — Theme name (e.g.,Material,Bootstrap).titleSettings(object) — Title and subtitle configuration.tooltipSettings(object) — Tooltip configuration (templates, enable, format).useGroupingSeparator(boolean) — Use grouping separator for numbers (e.g.,1,000). Default:trueweightValuePath(string) — Data field used to compute area/weight for each item.width(string|number) — Width of the TreeMap.
Methods
destroy()— Destroys the TreeMap instance and removes event listeners.doubleClickOnTreeMap(e)— Programmatically trigger double-click handling on the TreeMap.export(type, fileName, orientation, allowDownload)— Export the TreeMap inPNG|JPEG|SVG|PDF. Returns a Promise for some export flows (PDF).print(id)— Print TreeMap by passing an element id, DOM element, or list of ids.selectItem(levelOrder, isSelected)— Select or deselect items using alevelOrderarray identifying the item's path.
Events
beforePrint— Fired before printing/export is performed.click/itemClick— Fired when an item is clicked (include item details in args).doubleClick— Fired when an item is double-clicked.drillStart/drillEnd— Fired when drill-down begins and completes.itemRendering— Fired when an item is being rendered (use this to customize fill/label at render time).itemHighlight— Fired when an item is highlighted (hover or programmatic).itemMove— Fired when an item is moved (drag/drop related scenarios).itemSelected— Fired after an item is selected.legendItemRendering/legendRendering— Events during legend rendering.load/loaded— Lifecycle events fired before/after the component load.mouseMove/rightClick— Pointer interaction events providing mouse coordinates and target item.resize— Fired when component size changes.tooltipRendering— Fired when preparing tooltip content; modify tooltip text/template here.
Example — programmatic export & selection
import React, { useRef } from 'react';
const treemapRef = useRef(null);
// Export as PDF
treemapRef.current?.export('PDF', 'MyTreeMap');
// Select item by level order (example path)
treemapRef.current?.selectItem(['Country','State','City'], true);---
For complete and typed API definitions, including nested models (LeafItemSettingsModel, LevelSettingsModel, LegendSettingsModel, etc.), consult the official docs: https://ej2.syncfusion.com/react/documentation/api/treemap/index-default
Online references for complex models, methods and events
Use the links below to jump to the official, typed API documentation for complex nested models, key methods, and events used by TreeMap.
LeafItemSettingsModel: https://ej2.syncfusion.com/react/documentation/api/treemap/leafitemsettingsmodelLevelSettingsModel: https://ej2.syncfusion.com/react/documentation/api/treemap/levelsettingsmodelLegendSettingsModel: https://ej2.syncfusion.com/react/documentation/api/treemap/legendsettingsmodelTooltipSettingsModel: https://ej2.syncfusion.com/react/documentation/api/treemap/tooltipsettingsmodelSelectionSettingsModel: https://ej2.syncfusion.com/react/documentation/api/treemap/selectionsettingsmodelHighlightSettingsModel: https://ej2.syncfusion.com/react/documentation/api/treemap/highlightsettingsmodelTitleSettingsModel: https://ej2.syncfusion.com/react/documentation/api/treemap/titlesettingsmodelMarginModel: https://ej2.syncfusion.com/react/documentation/api/treemap/marginmodelInitialDrillSettingsModel: https://ej2.syncfusion.com/react/documentation/api/treemap/initialdrillsettingsmodelBorderModel: https://ej2.syncfusion.com/react/documentation/api/treemap/bordermodelQuery(DataManager query): https://ej2.syncfusion.com/react/documentation/api/data/data-manager#query
- Methods (TreeMap): https://ej2.syncfusion.com/react/documentation/api/treemap/index-default#methods
- Events (TreeMap): https://ej2.syncfusion.com/react/documentation/api/treemap/index-default#events
If you need inline anchor links for any additional nested model or a specific event signature, tell me which ones and I'll add them.
Color Mapping Strategies
Table of Contents
- Range Color Mapping
- Basic Range Mapping
- Sales Performance Gradient
- HeatMap Intensity
- Equal Value Color Mapping
- Category Colors
- Status Colors
- Department Colors
- Desaturation Color Mapping
- Opacity-Based Intensity
- Risk-Level Visualization
- Choosing Color Mapping Strategy
- Use Range Color Mapping When
- Use Equal Color Mapping When
- Use Desaturation When
- Common Patterns
- Pattern 1: Traffic Light Status
- Pattern 2: Multi-Metric with Ranges
- Pattern 3: Performance vs Target
- Tips for Effective Color Mapping
- Next Steps
Range Color Mapping
Range color mapping assigns colors based on value intervals. Items within a range get the specified color, creating a gradient effect.
Basic Range Mapping
import { TreeMapComponent } from '@syncfusion/ej2-react-treemap';
import * as React from "react";
const data = [
{ Fruit: 'Apple', Sales: 5000 },
{ Fruit: 'Mango', Sales: 3000 },
{ Fruit: 'Orange', Sales: 2300 },
{ Fruit: 'Banana', Sales: 500 },
{ Fruit: 'Grape', Sales: 4300 },
{ Fruit: 'Papaya', Sales: 1200 },
{ Fruit: 'Melon', Sales: 4500 }
];
<TreeMapComponent
dataSource={data}
weightValuePath="Sales"
rangeColorValuePath="Sales" // Color based on Sales values
leafItemSettings={{
labelPath: 'Fruit',
colorMapping: [
{ from: 500, to: 1500, color: '#FF6B6B' }, // Red
{ from: 1500, to: 3000, color: '#FFD93D' }, // Yellow
{ from: 3000, to: 5000, color: '#6BCB77' } // Green
]
}}
/>Result:
- Banana (500) → Red
- Orange (2300), Papaya (1200) → Yellow
- Mango (3000), Grape (4300), Apple (5000), Melon (4500) → Green
Sales Performance Gradient
const salesData = [
{ Region: 'North', Revenue: 45000 },
{ Region: 'South', Revenue: 28000 },
{ Region: 'East', Revenue: 52000 },
{ Region: 'West', Revenue: 38000 },
{ Region: 'Central', Revenue: 18000 }
];
<TreeMapComponent
dataSource={salesData}
weightValuePath="Revenue"
rangeColorValuePath="Revenue"
leafItemSettings={{
labelPath: 'Region',
colorMapping: [
{ from: 0, to: 20000, color: '#E74C3C' }, // Poor (Red)
{ from: 20000, to: 40000, color: '#F39C12' }, // Fair (Orange)
{ from: 40000, to: 60000, color: '#27AE60' } // Good (Green)
]
}}
/>Use case: Performance tiers where color represents achievement level.
HeatMap Intensity
const tempData = [
{ Region: 'Desert', Temperature: 55 },
{ Region: 'Tropical', Temperature: 32 },
{ Region: 'Arctic', Temperature: -40 },
{ Region: 'Temperate', Temperature: 15 }
];
<TreeMapComponent
dataSource={tempData}
rangeColorValuePath="Temperature"
leafItemSettings={{
labelPath: 'Region',
colorMapping: [
{ from: -50, to: 0, color: '#3498DB' }, // Blue (Cold)
{ from: 0, to: 20, color: '#2ECC71' }, // Green (Cool)
{ from: 20, to: 35, color: '#F39C12' }, // Orange (Warm)
{ from: 35, to: 60, color: '#E74C3C' } // Red (Hot)
]
}}
/>Equal Value Color Mapping
Equal color mapping assigns colors based on exact categorical values, not ranges. Perfect for categorical data.
Category Colors
const carData = [
{ Car: 'Mustang', Brand: 'Ford', Count: 232 },
{ Car: 'EcoSport', Brand: 'Ford', Count: 121 },
{ Car: 'Swift', Brand: 'Maruti', Count: 143 },
{ Car: 'Baleno', Brand: 'Maruti', Count: 454 },
{ Car: 'A3 Cabriolet', Brand: 'Audi', Count: 123 },
{ Car: 'RS7 Sportback', Brand: 'Audi', Count: 523 }
];
<TreeMapComponent
dataSource={carData}
weightValuePath="Count"
equalColorValuePath="Brand" // Color by Brand value
leafItemSettings={{
labelPath: 'Car',
colorMapping: [
{ value: 'Ford', color: '#3498DB' }, // Blue for Ford
{ value: 'Maruti', color: '#E74C3C' }, // Red for Maruti
{ value: 'Audi', color: '#2ECC71' } // Green for Audi
]
}}
/>Result: All Ford cars → Blue, all Maruti cars → Red, all Audi cars → Green.
Status Colors
const projectData = [
{ Project: 'Alpha', Team: 'Backend', Status: 'On Track', Tasks: 15 },
{ Project: 'Beta', Team: 'Frontend', Status: 'At Risk', Tasks: 12 },
{ Project: 'Gamma', Team: 'DevOps', Status: 'Blocked', Tasks: 8 },
{ Project: 'Delta', Team: 'QA', Status: 'On Track', Tasks: 20 }
];
<TreeMapComponent
dataSource={projectData}
weightValuePath="Tasks"
equalColorValuePath="Status"
leafItemSettings={{
labelPath: 'Project',
colorMapping: [
{ value: 'On Track', color: '#27AE60' }, // Green
{ value: 'At Risk', color: '#F39C12' }, // Orange
{ value: 'Blocked', color: '#E74C3C' } // Red
]
}}
/>Department Colors
const employeeData = [
{ Name: 'John', Department: 'Engineering', Count: 1 },
{ Name: 'Sarah', Department: 'Sales', Count: 1 },
{ Name: 'Mike', Department: 'HR', Count: 1 },
{ Name: 'Lisa', Department: 'Engineering', Count: 1 }
];
<TreeMapComponent
dataSource={employeeData}
equalColorValuePath="Department"
leafItemSettings={{
colorMapping: [
{ value: 'Engineering', color: '#9B59B6' },
{ value: 'Sales', color: '#3498DB' },
{ value: 'HR', color: '#E67E22' }
]
}}
/>Desaturation Color Mapping
Desaturation mapping applies opacity variation to a base color, creating lighter/darker shades based on values.
Opacity-Based Intensity
const data = [
{ Product: 'Laptop', Sales: 2500 },
{ Product: 'Phone', Sales: 3200 },
{ Product: 'Tablet', Sales: 1800 },
{ Product: 'Watch', Sales: 900 }
];
<TreeMapComponent
dataSource={data}
weightValuePath="Sales"
rangeColorValuePath="Sales"
leafItemSettings={{
labelPath: 'Product',
colorMapping: [
{
from: 900,
to: 3200,
color: '#3498DB',
minOpacity: 0.2, // Light blue for low values
maxOpacity: 1.0 // Full blue for high values
}
]
}}
/>Result:
- Watch (900) → Very light blue (0.2 opacity)
- Phone (3200) → Full blue (1.0 opacity)
- Others → Intermediate opacity based on sales
Risk-Level Visualization
const riskData = [
{ Project: 'A', Status: 'Risk', Level: 85 },
{ Project: 'B', Status: 'Risk', Level: 45 },
{ Project: 'C', Status: 'Risk', Level: 25 }
];
<TreeMapComponent
dataSource={riskData}
rangeColorValuePath="Level"
leafItemSettings={{
labelPath: 'Project',
colorMapping: [
{
from: 20,
to: 90,
color: '#E74C3C',
minOpacity: 0.3, // Light red = low risk
maxOpacity: 1.0 // Deep red = high risk
}
]
}}
/>Choosing Color Mapping Strategy
Use Range Color Mapping When:
- Visualizing continuous values: Revenue, temperature, performance scores
- Showing gradients: Low → Medium → High representation
- Comparing magnitude: Larger values show different color intensity
- Example: Heatmap-style visualization of quarterly sales
Use Equal Color Mapping When:
- Categorizing items: Brand, department, region, status
- Discrete categories: No gradient needed, each category has fixed color
- Quick visual identification: Users need instant category recognition
- Example: Different departments with distinct colors
Use Desaturation When:
- Subtle intensity variations: Want same hue, different saturation
- Professional appearance: Avoid too many distinct colors
- Print-friendly: Desaturation works better in grayscale printing
- Example: Risk levels (light red = low risk, dark red = high risk)
Common Patterns
Pattern 1: Traffic Light Status
const taskData = [
{ Task: 'Feature A', Progress: 85 },
{ Task: 'Feature B', Progress: 45 },
{ Task: 'Feature C', Progress: 25 }
];
<TreeMapComponent
dataSource={taskData}
weightValuePath="Progress"
rangeColorValuePath="Progress"
leafItemSettings={{
labelPath: 'Task',
colorMapping: [
{ from: 0, to: 33, color: '#E74C3C' }, // Red (Danger)
{ from: 33, to: 67, color: '#F39C12' }, // Yellow (Warning)
{ from: 67, to: 100, color: '#27AE60' } // Green (Success)
]
}}
/>Pattern 2: Multi-Metric with Ranges
const salesByRegion = [
{ Region: 'North', Q1: 30000, Q2: 35000, Q3: 40000, Avg: 35000 },
{ Region: 'South', Q1: 20000, Q2: 22000, Q3: 21000, Avg: 21000 },
{ Region: 'East', Q1: 45000, Q2: 48000, Q3: 52000, Avg: 48333 }
];
<TreeMapComponent
dataSource={salesByRegion}
weightValuePath="Avg"
rangeColorValuePath="Avg"
leafItemSettings={{
labelFormat: '${Region}\n${Avg}',
colorMapping: [
{ from: 0, to: 25000, color: '#BDC3C7' },
{ from: 25000, to: 40000, color: '#3498DB' },
{ from: 40000, to: 60000, color: '#27AE60' }
]
}}
/>Pattern 3: Performance vs Target
const performanceData = [
{ Team: 'Team A', Target: 100000, Actual: 95000, Percentage: 95 },
{ Team: 'Team B', Target: 80000, Actual: 92000, Percentage: 115 },
{ Team: 'Team C', Target: 120000, Actual: 85000, Percentage: 71 }
];
<TreeMapComponent
dataSource={performanceData}
rangeColorValuePath="Percentage"
leafItemSettings={{
labelPath: 'Team',
colorMapping: [
{ from: 0, to: 80, color: '#E74C3C' }, // Below target
{ from: 80, to: 100, color: '#F39C12' }, // Near target
{ from: 100, to: 150, color: '#27AE60' } // Above target
]
}}
/>Tips for Effective Color Mapping
1. Use color consistently: Same value should have same color across visualizations 2. Limit colors: Use 3-5 ranges for range mapping, avoid too many categories 3. Contrast: Ensure colors have enough contrast for visibility 4. Accessibility: Avoid red-green only combinations, support colorblind users 5. Legend: Always provide legend when using color mapping 6. Documentation: Explain color meaning to users (poor/fair/good, etc.)
Next Steps
- Leaf Items: See leaf-items-and-labels.md to customize label appearance
- Legends: See legends-tooltips-selection.md to add legends
- Drill-Down: See drilldown.md for hierarchical exploration
Customization, Accessibility & Export
Table of Contents
- Styling and Theming
- Built-in Themes
- Available Themes
- CSS Customization
- CSS Variables
- Dark Mode Support
- Accessibility Features
- WCAG 2.1 Compliance
- Keyboard Navigation
- Screen Reader Support
- Color Contrast
- Focus Indicators
- RTL Support
- Enable Right-to-Left Layout
- RTL with Arabic Labels
- Responsive RTL
- Internationalization
- Multi-Language Support
- Number and Date Formatting
- Multi-Language Tooltips
- Print and Export
- Export as Image
- Export Options
- Print TreeMap
- Export with Custom Styling
- Performance Optimization
- Data Aggregation for Performance
- Lazy Loading with Drill-Down
- Memoization for Performance
- Best Practices
- Accessibility Checklist
- Common Issues
- Next Steps
Styling and Theming
Built-in Themes
Syncfusion TreeMap includes several built-in themes:
import { TreeMapComponent } from '@syncfusion/ej2-react-treemap';
<TreeMapComponent
dataSource={data}
theme="Material" // Material, Bootstrap, Fluent, Tailwind, HighContrast
/>Available Themes
| Theme | Use Case | Characteristics |
|---|---|---|
| Material | Default, modern | Clean, material design |
| Bootstrap | Web apps | Professional, corporate |
| Fluent | Microsoft-like | Modern, accessible |
| Tailwind | Utility-first | Customizable, lightweight |
| HighContrast | Accessibility | High contrast for visibility |
CSS Customization
// Override TreeMap styles with CSS
const customCSS = `
.e-treemap {
font-family: 'Segoe UI', sans-serif;
}
.e-treemap-leaf {
border-radius: 4px;
box-shadow: 0 2px 4px rgba(0,0,0,0.1);
}
.e-treemap-label {
font-weight: 500;
}
`;
export function StyledTreeMap() {
return (
<>
<style>{customCSS}</style>
<TreeMapComponent
dataSource={data}
leafItemSettings={{ labelPath: 'Item' }}
/>
</>
);
}CSS Variables
// Use CSS variables for dynamic theming
const root = document.documentElement;
root.style.setProperty('--treemap-bg-color', '#f5f5f5');
root.style.setProperty('--treemap-text-color', '#333');
// In CSS
.e-treemap {
background-color: var(--treemap-bg-color);
color: var(--treemap-text-color);
}Dark Mode Support
export function DarkModeTreeMap() {
const [isDarkMode, setIsDarkMode] = React.useState(false);
React.useEffect(() => {
if (isDarkMode) {
document.body.classList.add('dark-mode');
import('@syncfusion/ej2-base/styles/material-dark.css');
} else {
document.body.classList.remove('dark-mode');
import('@syncfusion/ej2-base/styles/material.css');
}
}, [isDarkMode]);
return (
<div>
<button onClick={() => setIsDarkMode(!isDarkMode)}>
Toggle Dark Mode
</button>
<TreeMapComponent dataSource={data} />
</div>
);
}Accessibility Features
WCAG 2.1 Compliance
TreeMap supports WCAG 2.1 Level AA guidelines:
import { TreeMapComponent, Inject } from '@syncfusion/ej2-react-treemap';
<TreeMapComponent
dataSource={data}
leafItemSettings={{
labelPath: 'Item',
labelStyle: { size: '14px' } // Readable font size
}}
tooltipSettings={{
visible: true,
format: '${Item}: ${Value}' // Provide text alternatives
}}
>
<Inject services={[TreeMapSelection, TreeMapHighlight]} />
</TreeMapComponent>Keyboard Navigation
Enable keyboard navigation for assistive devices:
<TreeMapComponent
dataSource={data}
enableKeyboardNavigation={true} // Enable keyboard support
selectionSettings={{
mode: 'Item'
}}
/>Keyboard shortcuts:
- Tab: Navigate between items
- Enter/Space: Select/activate item
- Arrow Keys: Move between items
- Escape: Clear selection
Screen Reader Support
<TreeMapComponent
dataSource={data}
leafItemSettings={{
labelPath: 'Product',
labelFormat: '${Product}: ${Sales} units' // Meaningful labels
}}
tooltipSettings={{
visible: true,
format: '${Product}\nCategory: ${Category}\nSales: ${Sales} units'
}}
/>Color Contrast
Ensure sufficient contrast for visibility:
const accessibleColors = [
'#003f5c', // Dark blue - 9.5:1 contrast
'#bc5090', // Purple - 4.5:1 contrast
'#ffa600', // Orange - 3.1:1 contrast
];
<TreeMapComponent
palette={accessibleColors}
leafItemSettings={{
labelFontStyle: {
color: '#000', // High contrast text
size: '14px'
}
}}
/>Focus Indicators
const focusStyles = `
.e-treemap-leaf:focus {
outline: 3px solid #0066CC;
outline-offset: 2px;
}
`;
export function AccessibleTreeMap() {
return (
<>
<style>{focusStyles}</style>
<TreeMapComponent
dataSource={data}
/>
</>
);
}RTL Support
Enable Right-to-Left Layout
import { TreeMapComponent } from '@syncfusion/ej2-react-treemap';
export function RTLTreeMap() {
return (
<TreeMapComponent
dataSource={data}
enableRtl={true} // Enable RTL
leafItemSettings={{
labelPath: 'Item' // Labels will be RTL-aware
}}
legendSettings={{
visible: true,
position: 'Left' // Auto-adjusts for RTL
}}
/>
);
}RTL with Arabic Labels
const arabicData = [
{ الفئة: 'الإلكترونيات', المبيعات: 45000 },
{ الفئة: 'الملابس', المبيعات: 28000 },
{ الفئة: 'الأثاث', المبيعات: 35000 }
];
<TreeMapComponent
enableRtl={true}
dataSource={arabicData}
leafItemSettings={{
labelPath: 'الفئة'
}}
/>Responsive RTL
export function ResponsiveRTL() {
const [isRTL, setIsRTL] = React.useState(
document.documentElement.lang === 'ar'
);
return (
<TreeMapComponent
enableRtl={isRTL}
dataSource={data}
leafItemSettings={{ labelPath: 'Item' }}
/>
);
}Internationalization
Multi-Language Support
import { setCulture, loadCldr } from '@syncfusion/ej2-base';
// Load culture data
loadCldr(
require('cldr-data/main/ar/numbers.json'),
require('cldr-data/main/ar/currencies.json')
);
export function InternationalizedTreeMap() {
// Set culture
setCulture('ar'); // Arabic
// or 'es' for Spanish, 'fr' for French, etc.
return (
<TreeMapComponent
dataSource={data}
locale="ar"
leafItemSettings={{
labelFormat: '${Item}\n{0:C2}' // Currency format per locale
}}
/>
);
}Number and Date Formatting
export function FormattedNumbers() {
const data = [
{ Item: 'Product A', Sales: 1234567.89 },
{ Item: 'Product B', Sales: 987654.32 }
];
return (
<TreeMapComponent
dataSource={data}
locale="en-US"
leafItemSettings={{
labelFormat: '${Item}\n${Sales:C2}' // Formatted currency
}}
/>
);
}Multi-Language Tooltips
const translations = {
'en': {
item: 'Item',
sales: 'Sales',
category: 'Category'
},
'es': {
item: 'Artículo',
sales: 'Ventas',
category: 'Categoría'
},
'ar': {
item: 'عنصر',
sales: 'مبيعات',
category: 'فئة'
}
};
export function MultiLanguageTreeMap() {
const [language, setLanguage] = React.useState('en');
const t = translations[language];
return (
<TreeMapComponent
dataSource={data}
enableRtl={language === 'ar'}
tooltipSettings={{
format: `${t.item}: \${Item}<br>${t.sales}: \${Sales}`
}}
/>
);
}Print and Export
Export as Image
Important: Always include allowImageExport={true} prop and inject ImageExport service.
import { TreeMapComponent, ImageExport, Inject } from '@syncfusion/ej2-react-treemap';
import { ButtonComponent } from '@syncfusion/ej2-react-buttons';
export function ExportTreeMap() {
let treeMapInstance;
const handleExport = () => {
if (treeMapInstance) {
treeMapInstance.export('PNG', 'treemap'); // Export as PNG
}
};
return (
<div>
<ButtonComponent onClick={handleExport}>
Export as PNG
</ButtonComponent>
<TreeMapComponent
ref={g => treeMapInstance = g}
allowImageExport={true}
dataSource={data}
>
<Inject services={[ImageExport]} />
</TreeMapComponent>
</div>
);
}Export Options
// Export as SVG
treeMapInstance.export('SVG', 'treemap-chart');
// Export as PDF
treeMapInstance.export('PDF', 'treemap-document');
// Export with custom dimensions (for PNG)
treeMapInstance.export('PNG', 'treemap', 'Landscape', 1024, 768);Print TreeMap
Important: Always include allowPrint={true} prop and inject Print service.
import { TreeMapComponent, Print, Inject } from '@syncfusion/ej2-react-treemap';
import { ButtonComponent } from '@syncfusion/ej2-react-buttons';
export function PrintTreeMap() {
let treeMapInstance;
const handlePrint = () => {
if (treeMapInstance) {
treeMapInstance.print();
}
};
return (
<div>
<ButtonComponent onClick={handlePrint}>
Print
</ButtonComponent>
<TreeMapComponent
ref={g => treeMapInstance = g}
allowPrint={true}
dataSource={data}
>
<Inject services={[Print]} />
</TreeMapComponent>
</div>
);
}Combined Print and Export
import { TreeMapComponent, Print, ImageExport, Inject } from '@syncfusion/ej2-react-treemap';
import { ButtonComponent } from '@syncfusion/ej2-react-buttons';
export function PrintAndExportTreeMap() {
let treeMapInstance;
const handlePrint = () => {
if (treeMapInstance) {
treeMapInstance.print();
}
};
const handleExportPNG = () => {
if (treeMapInstance) {
treeMapInstance.export('PNG', 'treemap-report');
}
};
const handleExportPDF = () => {
if (treeMapInstance) {
treeMapInstance.export('PDF', 'treemap-report');
}
};
return (
<div>
<ButtonComponent onClick={handlePrint}>Print</ButtonComponent>
<ButtonComponent onClick={handleExportPNG}>Export PNG</ButtonComponent>
<ButtonComponent onClick={handleExportPDF}>Export PDF</ButtonComponent>
<TreeMapComponent
ref={g => treeMapInstance = g}
allowPrint={true}
allowImageExport={true}
dataSource={data}
height="500px"
>
<Inject services={[Print, ImageExport]} />
</TreeMapComponent>
</div>
);
}Performance Optimization
Data Aggregation for Performance
export function AggregatedData() {
const rawData = /* large dataset */;
// Aggregate similar items
const aggregated = rawData.reduce((acc, item) => {
const existing = acc.find(x => x.Category === item.Category);
if (existing) {
existing.Value += item.Value;
} else {
acc.push({ ...item });
}
return acc;
}, []);
return (
<TreeMapComponent
dataSource={aggregated}
height="350px"
/>
);
}Lazy Loading with Drill-Down
export function LazyLoadTreeMap() {
const [data, setData] = React.useState(initialData);
const handleDrillStart = async (args) => {
const childData = await fetchChildData(args.item.id);
setData([...data, ...childData]);
};
return (
<TreeMapComponent
enableDrillDown={true}
dataSource={data}
>
{/* Levels */}
</TreeMapComponent>
);
}Memoization for Performance
export const OptimizedTreeMap = React.memo(function TreeMap({ data }) {
return (
<TreeMapComponent
dataSource={data}
leafItemSettings={{ labelPath: 'Item' }}
/>
);
});Best Practices
1. Accessibility: Always include ARIA labels and keyboard navigation 2. Color: Use color-blind friendly palettes 3. Contrast: Maintain 4.5:1 minimum contrast ratio 4. Performance: Aggregate large datasets before rendering 5. Export: Provide export options for reports and sharing 6. i18n: Support multiple languages for global audiences 7. RTL: Test RTL functionality for Arabic/Hebrew users
Accessibility Checklist
- [ ] Color contrast meets WCAG AA standards
- [ ] Keyboard navigation enabled
- [ ] ARIA labels provided
- [ ] Tooltips contain meaningful information
- [ ] Font size ≥ 12px for readability
- [ ] Focus indicators visible (3px outline)
- [ ] Screen reader tested
- [ ] Print/export functionality works
Common Issues
Issue: RTL layout not applying
- Solution: Set
enableRtl={true}, verify CSS loaded correctly
Issue: Export creates blank image
- Solution: Ensure TreeMap fully rendered before export, add delay if needed
Issue: Translation text not displaying
- Solution: Verify culture data loaded, locale property matches
Next Steps
- Color Mapping: See color-mapping.md for accessible colors
- Legends: See legends-tooltips-selection.md for legend alternatives
- Data Binding: See data-binding.md for large dataset handling
Data Binding and Hierarchical Data
Table of Contents
- Understanding Weight Value Path
- Flat Data Binding
- Simple Category Comparison
- Market Share Visualization
- Hierarchical Data with Levels
- Two-Level Hierarchy
- Data Structure Notes
- Multi-Level Hierarchies
- Three-Level Organization Hierarchy
- Folder Structure Example
- Remote Data Sources
- Using Async/Await
- Data Transformation Before Binding
- Data Transformation Patterns
- Pattern 1: Aggregating Related Records
- Pattern 2: Filtering Data
- Pattern 3: Adding Calculated Properties
- Common Issues
- Next Steps
Understanding Weight Value Path
The weightValuePath property determines the size of each rectangle based on a numeric value from your data.
const data = [
{ Item: 'Laptop', Sales: 2500 }, // 2500 → rectangle area
{ Item: 'Phone', Sales: 3200 }, // 3200 → larger rectangle
{ Item: 'Tablet', Sales: 1800 } // 1800 → smaller rectangle
];
<TreeMapComponent
dataSource={data}
weightValuePath="Sales" // Use Sales values for sizing
leafItemSettings={{ labelPath: 'Item' }}
/>Key points:
- Must be a numeric property
- Proportional sizing: larger values → larger rectangles
- Negative values treated as zero
- Missing/undefined values default to 0
Flat Data Binding
Flat data has all items at the same level with no grouping:
Simple Category Comparison
const salesData = [
{ Region: 'North America', Revenue: 45000 },
{ Region: 'Europe', Revenue: 38000 },
{ Region: 'Asia Pacific', Revenue: 52000 },
{ Region: 'Latin America', Revenue: 28000 },
{ Region: 'Middle East', Revenue: 15000 }
];
<TreeMapComponent
height="350px"
dataSource={salesData}
weightValuePath="Revenue"
leafItemSettings={{
labelPath: 'Region'
}}
/>Result: Compares regional revenue with rectangle sizes proportional to revenue values.
Market Share Visualization
const marketData = [
{ Company: 'Apple', MarketCap: 2800 },
{ Company: 'Microsoft', MarketCap: 2500 },
{ Company: 'Google', MarketCap: 1800 },
{ Company: 'Amazon', MarketCap: 1600 },
{ Company: 'Tesla', MarketCap: 1000 }
];
<TreeMapComponent
dataSource={marketData}
weightValuePath="MarketCap"
leafItemSettings={{ labelPath: 'Company' }}
palette={['#3498db', '#e74c3c', '#2ecc71', '#f39c12', '#9b59b6']}
/>Use case: Compare market positions at a glance.
Hierarchical Data with Levels
Hierarchical data groups items into parent-child relationships. Use <LevelsDirective> to define hierarchy:
Two-Level Hierarchy
import { LevelsDirective, LevelDirective } from '@syncfusion/ej2-react-treemap';
const data = [
{ Country: 'USA', State: 'California', Sales: 2830 },
{ Country: 'USA', State: 'Texas', Sales: 2020 },
{ Country: 'USA', State: 'Florida', Sales: 1880 },
{ Country: 'Canada', State: 'Ontario', Sales: 1200 },
{ Country: 'Canada', State: 'British Columbia', Sales: 1100 }
];
<TreeMapComponent
dataSource={data}
weightValuePath="Sales"
leafItemSettings={{ labelPath: 'State' }}
>
<LevelsDirective>
<LevelDirective groupPath="Country" />
</LevelsDirective>
</TreeMapComponent>Result:
- Top-level groups by Country
- Within each country, shows individual states
- Rectangle sizes represent Sales values
Data Structure Notes
- Each record in data must have all hierarchy properties
groupPathorder determines hierarchy levels- Leaf items (innermost level) use
leafItemSettings.labelPath
Multi-Level Hierarchies
Support any depth of hierarchy for complex data structures:
Three-Level Organization Hierarchy
const orgData = [
{ Division: 'Engineering', Department: 'Backend', Team: 'API Services', HeadCount: 12 },
{ Division: 'Engineering', Department: 'Backend', Team: 'Database', HeadCount: 8 },
{ Division: 'Engineering', Department: 'Frontend', Team: 'Web', HeadCount: 10 },
{ Division: 'Engineering', Department: 'Frontend', Team: 'Mobile', HeadCount: 9 },
{ Division: 'Sales', Department: 'Enterprise', Team: 'Team A', HeadCount: 15 },
{ Division: 'Sales', Department: 'Enterprise', Team: 'Team B', HeadCount: 12 },
{ Division: 'Sales', Department: 'SMB', Team: 'Team C', HeadCount: 8 }
];
<TreeMapComponent
dataSource={orgData}
weightValuePath="HeadCount"
leafItemSettings={{
labelPath: 'Team',
labelFormat: '${Team}\n${HeadCount}hr'
}}
>
<LevelsDirective>
<LevelDirective groupPath="Division" />
<LevelDirective groupPath="Department" />
</LevelsDirective>
</TreeMapComponent>Structure:
- Level 1: Division (Engineering, Sales)
- Level 2: Department (Backend, Frontend, Enterprise, SMB)
- Leaf level: Team (individual teams)
Folder Structure Example
const fileSystem = [
{ Drive: 'C:', Folder: 'Documents', Subfolder: 'Work', Size: 2500 },
{ Drive: 'C:', Folder: 'Documents', Subfolder: 'Personal', Size: 1800 },
{ Drive: 'C:', Folder: 'Downloads', Subfolder: 'Apps', Size: 5000 },
{ Drive: 'D:', Folder: 'Media', Subfolder: 'Videos', Size: 15000 }
];
<TreeMapComponent
dataSource={fileSystem}
weightValuePath="Size"
leafItemSettings={{ labelPath: 'Subfolder' }}
>
<LevelsDirective>
<LevelDirective groupPath="Drive" />
<LevelDirective groupPath="Folder" />
</LevelsDirective>
</TreeMapComponent>Remote Data Sources
Fetch data from APIs and bind to TreeMap:
Using Async/Await
export function RemoteTreeMap() {
const [data, setData] = React.useState([]);
const [loading, setLoading] = React.useState(true);
React.useEffect(() => {
async function fetchData() {
try {
const response = await fetch('https://api.example.com/sales');
const result = await response.json();
setData(result);
} catch (error) {
console.error('Failed to load data:', error);
} finally {
setLoading(false);
}
}
fetchData();
}, []);
if (loading) return <div>Loading...</div>;
return (
<TreeMapComponent
height="350px"
dataSource={data}
weightValuePath="Sales"
leafItemSettings={{ labelPath: 'Region' }}
/>
);
}Data Transformation Before Binding
export function TransformedTreeMap() {
const [data, setData] = React.useState([]);
React.useEffect(() => {
async function loadAndTransform() {
const response = await fetch('https://api.example.com/products');
const rawData = await response.json();
// Transform flat API response to hierarchical format
const transformed = rawData.map(item => ({
Category: item.category,
Type: item.subcategory,
Product: item.name,
Sales: item.sales_amount
}));
setData(transformed);
}
loadAndTransform();
}, []);
return (
<TreeMapComponent
dataSource={data}
weightValuePath="Sales"
leafItemSettings={{ labelPath: 'Product' }}
>
<LevelsDirective>
<LevelDirective groupPath="Category" />
<LevelDirective groupPath="Type" />
</LevelsDirective>
</TreeMapComponent>
);
}Data Transformation Patterns
Pattern 1: Aggregating Related Records
Combine multiple records with same category into single weight:
const rawData = [
{ Region: 'USA', Quarter: 'Q1', Sales: 10000 },
{ Region: 'USA', Quarter: 'Q2', Sales: 12000 },
{ Region: 'USA', Quarter: 'Q3', Sales: 11500 },
{ Region: 'Canada', Quarter: 'Q1', Sales: 5000 }
];
// Transform to total sales per region
const aggregated = rawData.reduce((acc, item) => {
const existing = acc.find(r => r.Region === item.Region);
if (existing) {
existing.TotalSales += item.Sales;
} else {
acc.push({ Region: item.Region, TotalSales: item.Sales });
}
return acc;
}, []);
// Use aggregated data
<TreeMapComponent
dataSource={aggregated}
weightValuePath="TotalSales"
/>Pattern 2: Filtering Data
Show only items above a threshold:
const allData = [
{ Product: 'Laptop', Sales: 2500 },
{ Product: 'Mouse', Sales: 150 },
{ Product: 'Keyboard', Sales: 300 },
{ Product: 'Monitor', Sales: 1200 }
];
// Show only items with sales > 300
const filtered = allData.filter(item => item.Sales > 300);
<TreeMapComponent
dataSource={filtered}
weightValuePath="Sales"
/>Pattern 3: Adding Calculated Properties
Compute derived values for coloring or sizing:
const data = [
{ Product: 'A', Sold: 1000, Target: 1200 },
{ Product: 'B', Sold: 800, Target: 1000 },
{ Product: 'C', Sold: 950, Target: 900 }
];
// Add performance metrics
const enhanced = data.map(item => ({
...item,
Achievement: (item.Sold / item.Target) * 100,
Variance: item.Sold - item.Target
}));
<TreeMapComponent
dataSource={enhanced}
weightValuePath="Sold"
rangeColorValuePath="Achievement"
/>Common Issues
Issue: Rectangle sizes don't match weightValuePath values
- Cause: Non-numeric values in weight property
- Solution: Convert to numbers:
item.sales = Number(item.sales)
Issue: Hierarchy not showing correctly
- Cause: Missing groupPath properties in data
- Solution: Ensure all data records have every groupPath and leaf property
Issue: Performance slow with large datasets
- Cause: Too many items or levels
- Solution: Aggregate data, filter to top N items, or use virtual scrolling patterns
Next Steps
- Color Mapping: See color-mapping.md to color items by value
- Drill-Down: See drilldown.md to navigate hierarchies interactively
- Customization: See leaf-items-and-labels.md to customize appearance
Drill-Down and Navigation
Table of Contents
- Enabling Drill-Down
- Basic Drill-Down Example
- How It Works
- Multi-Level Hierarchies
- Three-Level Organization
- File System Hierarchy
- Drill-Down Events
- DrillStart Event (Before Drill-Down)
- DrillEnd Event (After Drill-Down)
- Complete Event Handler Example
- Navigation Patterns
- Pattern 1: Guided Drill-Down
- Pattern 2: Auto-Drill to Specific Level
- Pattern 3: Tracking Drill Path
- Breadcrumb Navigation
- Custom Breadcrumb Example
- Advanced Drill-Down
- Conditional Drill-Down Based on Selection
- Drill-Down with Dynamic Data Loading
- Best Practices
- Common Issues
- Next Steps
Enabling Drill-Down
Drill-down enables users to click on items to explore nested levels of hierarchical data.
Basic Drill-Down Example
import { TreeMapComponent, Inject } from '@syncfusion/ej2-react-treemap';
import { LevelsDirective, LevelDirective } from '@syncfusion/ej2-react-treemap';
const data = [
{ Country: 'USA', State: 'California', City: 'Los Angeles', Population: 3990456 },
{ Country: 'USA', State: 'California', City: 'San Francisco', Population: 884363 },
{ Country: 'USA', State: 'Texas', City: 'Houston', Population: 2320268 },
{ Country: 'USA', State: 'Texas', City: 'Dallas', Population: 1343573 },
{ Country: 'Canada', State: 'Ontario', City: 'Toronto', Population: 2930000 },
{ Country: 'Canada', State: 'British Columbia', City: 'Vancouver', Population: 640000 }
];
<TreeMapComponent
enableDrillDown={true} // Enable drill-down
dataSource={data}
weightValuePath="Population"
leafItemSettings={{ labelPath: 'City' }}
>
<LevelsDirective>
<LevelDirective groupPath="Country" />
<LevelDirective groupPath="State" />
</LevelsDirective>
</TreeMapComponent>Interaction: 1. Initial view shows countries (USA, Canada) 2. Click a country → shows states within that country 3. Click a state → shows cities within that state
How It Works
- enableDrillDown={true}: Activates click-to-drill behavior
- Levels define hierarchy: Each
<LevelDirective>is a depth level - Clicking: User clicks any item to drill into next level
- Back button: Header shows back option to return to previous level
Multi-Level Hierarchies
Support any number of hierarchy levels for complex data exploration.
Three-Level Organization
const orgData = [
{ Company: 'Tech Corp', Division: 'Engineering', Department: 'Backend', Team: 'API Services', Members: 12 },
{ Company: 'Tech Corp', Division: 'Engineering', Department: 'Backend', Team: 'Database', Members: 8 },
{ Company: 'Tech Corp', Division: 'Engineering', Department: 'Frontend', Team: 'Web', Members: 10 },
{ Company: 'Tech Corp', Division: 'Sales', Department: 'Enterprise', Team: 'Team A', Members: 15 },
{ Company: 'Tech Corp', Division: 'Sales', Department: 'Enterprise', Team: 'Team B', Members: 12 }
];
<TreeMapComponent
enableDrillDown={true}
dataSource={orgData}
weightValuePath="Members"
leafItemSettings={{ labelPath: 'Team' }}
>
<LevelsDirective>
<LevelDirective groupPath="Division" />
<LevelDirective groupPath="Department" />
</LevelsDirective>
</TreeMapComponent>Navigation Flow:
- Level 0: Shows divisions (Engineering, Sales)
- Level 1: Shows departments within selected division
- Leaf level: Shows teams within selected department
File System Hierarchy
const fileSystemData = [
{ Drive: 'C:', Folder: 'Users', SubFolder: 'Documents', File: 'Resume.pdf', Size: 256 },
{ Drive: 'C:', Folder: 'Users', SubFolder: 'Documents', File: 'CoverLetter.docx', Size: 128 },
{ Drive: 'C:', Folder: 'Users', SubFolder: 'Downloads', File: 'Setup.exe', Size: 5120 },
{ Drive: 'D:', Folder: 'Projects', SubFolder: 'WebApp', File: 'App.jsx', Size: 64 },
{ Drive: 'D:', Folder: 'Media', SubFolder: 'Videos', File: 'Tutorial.mp4', Size: 512000 }
];
<TreeMapComponent
enableDrillDown={true}
dataSource={fileSystemData}
weightValuePath="Size"
leafItemSettings={{
labelPath: 'File',
labelFormat: '${File}\n${Size}KB'
}}
>
<LevelsDirective>
<LevelDirective groupPath="Drive" />
<LevelDirective groupPath="Folder" />
<LevelDirective groupPath="SubFolder" />
</LevelsDirective>
</TreeMapComponent>Drill-Down Events
Handle drill-down interactions with events to customize behavior.
DrillStart Event (Before Drill-Down)
export function TreeMapWithEvents() {
const handleDrillStart = (args) => {
console.log('Drilling into:', args.rowIndex);
// args.rowIndex: index of clicked item
// Can prevent drill-down if needed: args.cancel = true
};
return (
<TreeMapComponent
enableDrillDown={true}
dataSource={data}
onDrillStart={handleDrillStart}
>
{/* Levels */}
</TreeMapComponent>
);
}DrillEnd Event (After Drill-Down)
export function TreeMapDrillEnd() {
const [currentLevel, setCurrentLevel] = React.useState('root');
const handleDrillEnd = (args) => {
console.log('Current level:', args.currentLevel);
setCurrentLevel(args.currentLevel);
// Update UI or trigger data loading
};
return (
<div>
<div>Current Level: {currentLevel}</div>
<TreeMapComponent
enableDrillDown={true}
dataSource={data}
onDrillEnd={handleDrillEnd}
>
{/* Levels */}
</TreeMapComponent>
</div>
);
}Complete Event Handler Example
export function TreeMapEventHandling() {
const [itemCount, setItemCount] = React.useState(0);
const handleDrillStart = (args) => {
console.log('Starting drill-down');
};
const handleDrillEnd = (args) => {
// Update UI based on new level
const visibleItems = args.drillDownItems?.length || 0;
setItemCount(visibleItems);
console.log(`Drilled to level with ${visibleItems} items`);
};
return (
<div>
<div>Visible Items: {itemCount}</div>
<TreeMapComponent
enableDrillDown={true}
dataSource={data}
onDrillStart={handleDrillStart}
onDrillEnd={handleDrillEnd}
>
{/* Levels */}
</TreeMapComponent>
</div>
);
}Navigation Patterns
Pattern 1: Guided Drill-Down
Only allow drilling into specific items:
export function GuidedDrillDown() {
const handleDrillStart = (args) => {
// Only allow drilling if item meets criteria
const item = args.item;
if (item.Members === undefined) {
args.cancel = true; // Prevent drill-down
alert('Cannot drill into leaf items');
}
};
return (
<TreeMapComponent
enableDrillDown={true}
dataSource={data}
onDrillStart={handleDrillStart}
>
{/* Levels */}
</TreeMapComponent>
);
}Pattern 2: Auto-Drill to Specific Level
Automatically drill when clicking certain items:
export function AutoDrill() {
const treeMapRef = React.useRef(null);
const handleDrillStart = (args) => {
// Auto-drill if only one child exists
if (args.drillDownItems?.length === 1) {
setTimeout(() => {
treeMapRef.current?.drillDown(args.item, 0);
}, 0);
}
};
return (
<TreeMapComponent
ref={treeMapRef}
enableDrillDown={true}
dataSource={data}
onDrillStart={handleDrillStart}
>
{/* Levels */}
</TreeMapComponent>
);
}Pattern 3: Tracking Drill Path
Track user's navigation path:
export function TrackDrillPath() {
const [drillPath, setDrillPath] = React.useState(['Root']);
const handleDrillEnd = (args) => {
const pathItems = args.item ? [...drillPath, args.item.label] : ['Root'];
setDrillPath(pathItems);
};
return (
<div>
<div>Path: {drillPath.join(' > ')}</div>
<TreeMapComponent
enableDrillDown={true}
dataSource={data}
onDrillEnd={handleDrillEnd}
>
{/* Levels */}
</TreeMapComponent>
</div>
);
}Breadcrumb Navigation
Show breadcrumb for current drill location:
Custom Breadcrumb Example
export function TreeMapWithBreadcrumb() {
const [breadcrumb, setBreadcrumb] = React.useState(['Root']);
const treeMapRef = React.useRef(null);
const handleDrillEnd = (args) => {
const newPath = [...breadcrumb, args.item?.label || 'Item'];
setBreadcrumb(newPath);
};
const handleBreadcrumbClick = (index) => {
// Return to previous level
const newBreadcrumb = breadcrumb.slice(0, index + 1);
setBreadcrumb(newBreadcrumb);
// Implement back navigation logic
// treeMapRef.current?.goBack();
};
return (
<div>
<div style={{ padding: '10px', marginBottom: '10px' }}>
{breadcrumb.map((item, index) => (
<span key={index}>
<a
href="#"
onClick={() => handleBreadcrumbClick(index)}
style={{ cursor: 'pointer' }}
>
{item}
</a>
{index < breadcrumb.length - 1 && ' > '}
</span>
))}
</div>
<TreeMapComponent
ref={treeMapRef}
enableDrillDown={true}
dataSource={data}
onDrillEnd={handleDrillEnd}
>
{/* Levels */}
</TreeMapComponent>
</div>
);
}Advanced Drill-Down
Conditional Drill-Down Based on Selection
export function ConditionalDrillDown() {
const [selectedCategory, setSelectedCategory] = React.useState(null);
const handleItemClick = (args) => {
setSelectedCategory(args.item?.label);
};
const handleDrillStart = (args) => {
// Only allow drill-down for selected category
if (selectedCategory && args.item?.label !== selectedCategory) {
args.cancel = true;
}
};
return (
<TreeMapComponent
enableDrillDown={true}
dataSource={data}
onItemClick={handleItemClick}
onDrillStart={handleDrillStart}
>
{/* Levels */}
</TreeMapComponent>
);
}Drill-Down with Dynamic Data Loading
export function DynamicDrillDown() {
const [data, setData] = React.useState(initialData);
const handleDrillStart = async (args) => {
const selectedItem = args.item;
// Load child data from API
try {
const response = await fetch(`/api/children/${selectedItem.id}`);
const childData = await response.json();
// Merge child data with existing data
setData([...data, ...childData]);
} catch (error) {
console.error('Failed to load child data:', error);
args.cancel = true;
}
};
return (
<TreeMapComponent
enableDrillDown={true}
dataSource={data}
onDrillStart={handleDrillStart}
>
{/* Levels */}
</TreeMapComponent>
);
}Best Practices
1. Clear hierarchy: Use 2-4 levels for best user experience 2. Meaningful labels: Make drill paths understandable 3. Visual feedback: Show current location clearly 4. Back option: Always allow returning to previous level 5. Data loading: For large datasets, consider lazy loading on drill 6. Mobile consideration: Ensure drill-down works on touch devices
Common Issues
Issue: Back button doesn't appear
- Solution: Ensure enableDrillDown={true} and hierarchy levels defined
Issue: Can't drill into certain items
- Solution: Check that onDrillStart doesn't cancel drill; verify data has children
Issue: Drill-down very slow
- Solution: Reduce data size, use pagination, or implement lazy loading
Next Steps
- Leaf Items: See leaf-items-and-labels.md for label formatting
- Layouts: See layouts.md to optimize hierarchy display
- Color Mapping: See color-mapping.md to distinguish levels
Getting Started with TreeMap
Table of Contents
- Installation
- Dependencies
- Package Setup
- Basic Project Setup
- TypeScript Setup
- Module Injection
- Available Modules
- First TreeMap Render
- Minimal Example
- Understanding the Props
- Binding Data
- Flat Data Structure
- Hierarchical Data Structure
- Data Binding Tips
- Next Steps
Installation
Install the Syncfusion React TreeMap package using npm:
npm install @syncfusion/ej2-react-treemap --saveDependencies
The TreeMap package has the following peer dependencies:
@syncfusion/ej2-treemap
@syncfusion/ej2-base
@syncfusion/ej2-data
@syncfusion/ej2-pdf-export
@syncfusion/ej2-svg-base
@syncfusion/ej2-react-baseThese are automatically installed with the main package.
Package Setup
Basic Project Setup
For optimal development experience, use Vite instead of Create React App:
# Create a new Vite React app
npm create vite@latest my-treemap-app -- --template react
cd my-treemap-app
# Install Syncfusion TreeMap
npm install @syncfusion/ej2-react-treemap --save
# Start development server
npm run devTypeScript Setup
For TypeScript projects:
npm create vite@latest my-treemap-app -- --template react-ts
cd my-treemap-app
npm install @syncfusion/ej2-react-treemap --save
npm run devModule Injection
TreeMap uses feature-based modules. Import and inject required feature modules for your use case:
import { TreeMapComponent, Inject } from '@syncfusion/ej2-react-treemap';
import {
TreeMapHighlight,
TreeMapSelection,
TreeMapLegend,
TreeMapTooltip
} from '@syncfusion/ej2-react-treemap';
export function MyTreeMap() {
return (
<TreeMapComponent>
<Inject services={[TreeMapHighlight, TreeMapSelection, TreeMapLegend, TreeMapTooltip]} />
</TreeMapComponent>
);
}Available Modules
| Module | Feature | When to Use |
|---|---|---|
TreeMapHighlight | Highlight items on hover | Interactive visualization |
TreeMapSelection | Select items with click | Data selection interactions |
TreeMapLegend | Display legend | Large datasets with categories |
TreeMapTooltip | Show tooltips on hover | Detailed information display |
Note: Inject modules only when needed to minimize bundle size.
First TreeMap Render
Minimal Example
import * as React from 'react';
import { TreeMapComponent } from '@syncfusion/ej2-react-treemap';
export function TreeMapBasic() {
const data = [
{ Title: 'Apple', Sales: 5000 },
{ Title: 'Mango', Sales: 3000 },
{ Title: 'Orange', Sales: 2300 },
{ Title: 'Banana', Sales: 500 },
{ Title: 'Grape', Sales: 4300 },
{ Title: 'Papaya', Sales: 1200 },
{ Title: 'Melon', Sales: 4500 }
];
return (
<TreeMapComponent
height="350px"
dataSource={data}
weightValuePath="Sales"
leafItemSettings={{
labelPath: 'Title'
}}
/>
);
}Result: Renders a TreeMap with rectangular items sized by Sales value, labeled with Title.
Understanding the Props
- height: Container height (required)
- dataSource: Array of data objects to visualize
- weightValuePath: Property name determining rectangle size
- leafItemSettings: Configuration for leaf (lowest level) items
- labelPath: Property name for item labels
Binding Data
Flat Data Structure
Flat data has no nesting—all items at the same level:
const flatData = [
{ Product: 'Laptop', Sales: 2500 },
{ Product: 'Phone', Sales: 3200 },
{ Product: 'Tablet', Sales: 1800 },
{ Product: 'Watch', Sales: 900 }
];
<TreeMapComponent
dataSource={flatData}
weightValuePath="Sales"
leafItemSettings={{ labelPath: 'Product' }}
/>Use case: Simple category-based comparisons without hierarchy.
Hierarchical Data Structure
Hierarchical data contains parent-child relationships:
const hierarchicalData = [
{ Category: 'Fruits', Type: 'Tropical', Item: 'Mango', Sales: 3000 },
{ Category: 'Fruits', Type: 'Tropical', Item: 'Banana', Sales: 500 },
{ Category: 'Fruits', Type: 'Citrus', Item: 'Orange', Sales: 2300 },
{ Category: 'Fruits', Type: 'Citrus', Item: 'Lemon', Sales: 1200 }
];
import { LevelsDirective, LevelDirective } from '@syncfusion/ej2-react-treemap';
<TreeMapComponent
dataSource={hierarchicalData}
weightValuePath="Sales"
leafItemSettings={{ labelPath: 'Item' }}
>
<LevelsDirective>
<LevelDirective groupPath="Category" />
<LevelDirective groupPath="Type" />
</LevelsDirective>
</TreeMapComponent>Use case: Exploring nested categories (e.g., regions → states → cities).
Data Binding Tips
- weightValuePath: Must reference a numeric property for proper sizing
- labelPath in leafItemSettings: Required to display item labels
- groupPath in Levels: Define hierarchy order (top level first)
- Empty data: TreeMap renders empty but no error occurs
Next Steps
- Color Mapping: See color-mapping.md for applying colors to items
- Hierarchies: See drilldown.md for multi-level exploration
- Layouts: See layouts.md for different spatial arrangements
TreeMap Layouts
Table of Contents
- Layout Types
- Squarified Layout
- Basic Squarified Example
- Market Dominance Visualization
- Horizontal Layout
- Horizontal Layout Example
- Budget Distribution Example
- Vertical Layout
- Vertical Layout Example
- Storage Usage Visualization
- Slice and Dice Layout
- SliceAndDice Example
- Choosing the Right Layout
- Use Squarified When
- Use Horizontal When
- Use Vertical When
- Use SliceAndDice When
- Dynamic Layout Selection
- Responsive Layout Based on Container
- Layout Based on Data Size
- Layout Comparison View
- Layout Performance Tips
- Common Issues
- Next Steps
Layout Types
TreeMap supports four layout algorithms that determine how rectangles are arranged. Each layout has different characteristics affecting aspect ratio, readability, and visual appeal.
| Layout | Aspect Ratio | Best For | Algorithm |
|---|---|---|---|
| Squarified | Balanced | General purpose, balanced aspect ratios | Optimizes for square-like rectangles |
| Horizontal | Wide/narrow | Comparing similar-sized items | Left-to-right ordering |
| Vertical | Tall/narrow | Category hierarchies | Top-to-bottom ordering |
| SliceAndDice | Variable | Exploring hierarchies | Alternating rows/columns |
Squarified Layout
Squarified (default) layout creates rectangles with balanced aspect ratios, approximately square-shaped.
Basic Squarified Example
import { TreeMapComponent } from '@syncfusion/ej2-react-treemap';
const data = [
{ Fruit: 'Apple', Count: 5000 },
{ Fruit: 'Mango', Count: 3000 },
{ Fruit: 'Orange', Count: 2300 },
{ Fruit: 'Banana', Count: 500 },
{ Fruit: 'Grape', Count: 4300 }
];
<TreeMapComponent
height="350px"
dataSource={data}
weightValuePath="Count"
layoutType="Squarified" // Default layout
leafItemSettings={{ labelPath: 'Fruit' }}
/>Characteristics:
- Aspect ratios close to 1:1 (square-like)
- Most visually balanced
- Best for general-purpose visualization
- Improved readability for varied data sizes
Market Dominance Visualization
const marketData = [
{ Company: 'Samsung', MarketShare: 25 },
{ Company: 'Apple', MarketShare: 20 },
{ Company: 'Xiaomi', MarketShare: 15 },
{ Company: 'Oppo', MarketShare: 12 },
{ Company: 'Vivo', MarketShare: 10 },
{ Company: 'Others', MarketShare: 18 }
];
<TreeMapComponent
dataSource={marketData}
weightValuePath="MarketShare"
layoutType="Squarified"
leafItemSettings={{
labelPath: 'Company',
labelFormat: '${Company}\n${MarketShare}%'
}}
/>Horizontal Layout
Horizontal layout arranges items in rows, creating wide rectangles, left-to-right ordering.
Horizontal Layout Example
const regionData = [
{ Region: 'Asia', Sales: 45000 },
{ Region: 'Europe', Sales: 38000 },
{ Region: 'Americas', Sales: 52000 },
{ Region: 'Africa', Sales: 15000 },
{ Region: 'Oceania', Sales: 8000 }
];
<TreeMapComponent
dataSource={regionData}
weightValuePath="Sales"
layoutType="SliceAndDiceHorizontal"
leafItemSettings={{
labelPath: 'Region',
labelFormat: '${Region}\n${Sales}'
}}
/>Characteristics:
- Creates horizontal row-like layout
- Good for top-to-bottom reading
- Items ordered left-to-right
- Better for items with wide aspect ratios
Budget Distribution Example
const budgetData = [
{ Department: 'Engineering', Budget: 500000 },
{ Department: 'Marketing', Budget: 250000 },
{ Department: 'Sales', Budget: 300000 },
{ Department: 'Operations', Budget: 150000 },
{ Department: 'HR', Budget: 100000 }
];
<TreeMapComponent
dataSource={budgetData}
weightValuePath="Budget"
layoutType="SliceAndDiceHorizontal"
leafItemSettings={{
labelPath: 'Department'
}}
palette={['#3498DB', '#E74C3C', '#2ECC71', '#F39C12', '#9B59B6']}
/>Vertical Layout
Vertical layout arranges items in columns, creating tall rectangles, top-to-bottom ordering.
Vertical Layout Example
const categoryData = [
{ Category: 'Electronics', Sales: 45000 },
{ Category: 'Clothing', Sales: 35000 },
{ Category: 'Books', Sales: 28000 },
{ Category: 'Furniture', Sales: 52000 },
{ Category: 'Sports', Sales: 18000 }
];
<TreeMapComponent
dataSource={categoryData}
weightValuePath="Sales"
layoutType="SliceAndDiceVertical"
leafItemSettings={{
labelPath: 'Category'
}}
/>Characteristics:
- Creates vertical column-like layout
- Items ordered top-to-bottom, left-to-right
- Better for narrower containers
- Emphasizes vertical reading flow
Storage Usage Visualization
const storageData = [
{ Folder: 'Documents', Size: 25000 },
{ Folder: 'Photos', Size: 350000 },
{ Folder: 'Videos', Size: 1500000 },
{ Folder: 'Music', Size: 250000 },
{ Folder: 'Downloads', Size: 500000 }
];
<TreeMapComponent
height="500px"
dataSource={storageData}
weightValuePath="Size"
layoutType="SliceAndDiceVertical"
leafItemSettings={{
labelPath: 'Folder',
labelFormat: '${Folder}\n${Size} MB'
}}
/>Slice and Dice Layout
Slice and Dice layout alternates between horizontal and vertical divisions, useful for hierarchical data.
SliceAndDice Example
import { LevelsDirective, LevelDirective } from '@syncfusion/ej2-react-treemap';
const hierarchicalData = [
{ Company: 'TechCorp', Division: 'Software', Department: 'Frontend', Headcount: 45 },
{ Company: 'TechCorp', Division: 'Software', Department: 'Backend', Headcount: 60 },
{ Company: 'TechCorp', Division: 'Hardware', Department: 'R&D', Headcount: 35 },
{ Company: 'TechCorp', Division: 'Hardware', Department: 'Manufacturing', Headcount: 80 }
];
<TreeMapComponent
dataSource={hierarchicalData}
weightValuePath="Headcount"
layoutType="SliceAndDiceAuto"
leafItemSettings={{ labelPath: 'Department' }}
>
<LevelsDirective>
<LevelDirective groupPath="Division" />
</LevelsDirective>
</TreeMapComponent>Characteristics:
- Alternates horizontal and vertical divisions
- Good for hierarchies with many levels
- Creates clear visual separation
- Useful for file system or org chart visualization
Choosing the Right Layout
Use Squarified When:
- Visual balance is priority: Want aesthetically pleasing visualization
- Mixed-size data: Items vary significantly in size
- General exploration: Users exploring data without specific reading pattern
- Example: Market share, product comparison
<TreeMapComponent
layoutType="Squarified" // Default, good choice
/>Use Horizontal When:
- Reading left-to-right: Users accustomed to horizontal scanning
- Many items: Large number of categories to display
- Label space: Need horizontal space for item labels
- Example: Budget distribution, regional comparison
<TreeMapComponent
layoutType="SliceAndDiceHorizontal" // Best for label readability
/>Use Vertical When:
- Tall containers: Container height > width
- Hierarchical exploration: Parent-child relationships matter
- Column-based reading: Users naturally read top-to-bottom
- Example: Folder structure, category hierarchy
<TreeMapComponent
layoutType="SliceAndDiceVertical" // Fits tall viewports
/>Use SliceAndDice When:
- Deep hierarchies: Multiple levels of grouping
- Clear separation needed: Distinguish parent groups visually
- Alternating logic: Want alternating row/column arrangement
- Example: Organization chart, file system
<TreeMapComponent
layoutType="SliceAndDiceAuto" // For hierarchical data
>
<LevelsDirective>
{/* Multiple level groups */}
</LevelsDirective>
</TreeMapComponent>Dynamic Layout Selection
Responsive Layout Based on Container
export function ResponsiveTreeMap() {
const containerRef = React.useRef(null);
const [layout, setLayout] = React.useState('Squarified');
React.useEffect(() => {
function handleResize() {
const width = containerRef.current?.offsetWidth || 0;
const height = containerRef.current?.offsetHeight || 0;
// Wide container → Horizontal
if (width > height * 1.5) {
setLayout('Horizontal');
}
// Tall container → Vertical
else if (height > width * 1.5) {
setLayout('Vertical');
}
// Balanced → Squarified
else {
setLayout('Squarified');
}
}
handleResize();
window.addEventListener('resize', handleResize);
return () => window.removeEventListener('resize', handleResize);
}, []);
return (
<div ref={containerRef} style={{ width: '100%', height: '100vh' }}>
<TreeMapComponent
dataSource={data}
layoutType={layout}
height="100%"
/>
</div>
);
}Layout Based on Data Size
export function AdaptiveTreeMap({ data }) {
// Choose layout based on number of items
const getLayout = () => {
if (data.length > 100) return 'SliceAndDice'; // Many items
if (data.length > 30) return 'Horizontal'; // Many items
return 'Squarified'; // Few items
};
return (
<TreeMapComponent
dataSource={data}
layoutType={getLayout()}
/>
);
}Layout Comparison View
export function CompareLayouts({ data }) {
const layouts = ['Squarified', 'Horizontal', 'Vertical', 'SliceAndDice'];
return (
<div style={{ display: 'grid', gridTemplateColumns: '1fr 1fr', gap: '20px' }}>
{layouts.map(layout => (
<div key={layout}>
<h3>{layout}</h3>
<TreeMapComponent
dataSource={data}
layoutType={layout}
height="300px"
/>
</div>
))}
</div>
);
}Layout Performance Tips
1. Squarified: Best default, good performance for any data 2. Horizontal/Vertical: Linear calculation, slightly faster than squarified 3. SliceAndDice: Best for hierarchies, consider for deep nesting 4. Large datasets: All layouts perform similarly; optimize data instead
Common Issues
Issue: Labels overlapping in horizontal layout
- Solution: Increase container width or use label templates to format
Issue: Rectangles too narrow/wide in vertical layout
- Solution: Consider container proportions or switch to Squarified
Issue: Layout doesn't match expectations
- Solution: Verify
layoutTypeprop spelling (case-sensitive)
Next Steps
- Drill-Down: See drilldown.md for hierarchical navigation
- Color Mapping: See color-mapping.md to add visual distinction
- Labels: See leaf-items-and-labels.md for label positioning
Leaf Items, Labels & Templates
Table of Contents
- Leaf Item Configuration
- Basic Configuration
- Core Leaf Item Properties
- Label Positioning
- Available Positions
- Position Examples
- Choosing Label Position
- Data Labels and Formatting
- Simple Label Format
- Multi-Line Labels
- Calculated Properties in Label
- Currency and Number Formatting
- Label Templates
- Template-Based Label
- Rich Content Template
- Text Wrapping & Overflow
- Word Wrapping
- Wrapping Options
- Handling Small Rectangles
- Border and Fill Customization
- Individual Item Styling
- Border Configuration
- Gradient Borders for Hierarchy Levels
- Advanced Customization
- Pattern 1: Size-Responsive Font
- Pattern 2: Highlight Important Items
- Pattern 3: Icon-Based Labels
- Pattern 4: Percentage Display
- Best Practices
- Common Issues
- Next Steps
Leaf Item Configuration
Leaf items are the innermost/lowest-level items in the TreeMap hierarchy. Configure them with leafItemSettings.
Basic Configuration
import { TreeMapComponent } from '@syncfusion/ej2-react-treemap';
const data = [
{ Fruit: 'Apple', Count: 5000 },
{ Fruit: 'Mango', Count: 3000 },
{ Fruit: 'Orange', Count: 2300 }
];
<TreeMapComponent
dataSource={data}
weightValuePath="Count"
leafItemSettings={{
labelPath: 'Fruit', // Display property
fill: '#FF6B6B', // Background color
border: {
color: '#333',
width: 2
}
}}
/>Core Leaf Item Properties
| Property | Type | Purpose |
|---|---|---|
labelPath | string | Data property to display as label |
fill | string | Background color of item |
labelFormat | string | Format template for label |
border | object | Border configuration |
labelPosition | string | Label placement position |
labelFontStyle | object | Font styling for labels |
Label Positioning
Control where labels appear within rectangles.
Available Positions
const positions = [
'TopLeft', // Top-left corner
'TopCenter', // Top center
'TopRight', // Top-right corner
'CenterLeft', // Middle left
'Center', // Center (default)
'CenterRight', // Middle right
'BottomLeft', // Bottom-left corner
'BottomCenter', // Bottom center
'BottomRight' // Bottom-right corner
];Position Examples
const data = [
{ Item: 'A', Value: 100 },
{ Item: 'B', Value: 200 }
];
// Top-left positioning
<TreeMapComponent
dataSource={data}
leafItemSettings={{
labelPath: 'Item',
labelPosition: 'TopLeft'
}}
/>
// Center positioning (default)
<TreeMapComponent
dataSource={data}
leafItemSettings={{
labelPath: 'Item',
labelPosition: 'Center'
}}
/>
// Bottom-right positioning
<TreeMapComponent
dataSource={data}
leafItemSettings={{
labelPath: 'Item',
labelPosition: 'BottomRight'
}}
/>Choosing Label Position
- Center: Best for balanced rectangles
- TopLeft/TopRight: Good for wide rectangles
- BottomLeft/BottomRight: For hierarchical visualization
- CenterLeft/CenterRight: For tall rectangles
Data Labels and Formatting
Format labels to display multiple data properties:
Simple Label Format
const salesData = [
{ Region: 'North', Sales: 45000 },
{ Region: 'South', Sales: 28000 }
];
<TreeMapComponent
dataSource={salesData}
weightValuePath="Sales"
leafItemSettings={{
labelFormat: '${Region}' // Only region name
}}
/>Multi-Line Labels
const productData = [
{ Product: 'Laptop', Sales: 2500, Profit: 800 },
{ Product: 'Phone', Sales: 3200, Profit: 1200 }
];
<TreeMapComponent
dataSource={productData}
leafItemSettings={{
labelFormat: '${Product}\n${Sales}', // Product on line 1, Sales on line 2
labelFontStyle: {
size: '14px',
fontFamily: 'Arial'
}
}}
/>Calculated Properties in Label
<TreeMapComponent
dataSource={data}
leafItemSettings={{
labelFormat: '${Item}: ${Value} units'
}}
/>Currency and Number Formatting
const data = [
{ Category: 'Electronics', Revenue: 125000.50 },
{ Category: 'Clothing', Revenue: 87500.25 }
];
<TreeMapComponent
dataSource={data}
leafItemSettings={{
labelFormat: '${Category}\n$${Revenue}' // Dollar sign prefix
}}
/>Label Templates
Use custom templates for complex label rendering:
Template-Based Label
export function TemplateBasedLabels() {
const labelTemplate = (props) => {
return (
<div style={{
padding: '5px',
textAlign: 'center',
fontSize: '12px'
}}>
<div style={{ fontWeight: 'bold' }}>
{props.label}
</div>
<div style={{ fontSize: '10px', color: '#666' }}>
{props.value}
</div>
</div>
);
};
return (
<TreeMapComponent
dataSource={data}
leafItemSettings={{
labelTemplate: labelTemplate
}}
/>
);
}Rich Content Template
export function RichLabelTemplate() {
const data = [
{ Item: 'Product A', Sales: 2500, Growth: '+12%' },
{ Item: 'Product B', Sales: 3200, Growth: '+8%' }
];
const labelTemplate = (props) => {
const isGrowing = props.Growth?.includes('+');
return (
<div style={{
width: '100%',
height: '100%',
display: 'flex',
flexDirection: 'column',
justifyContent: 'center',
alignItems: 'center',
color: 'white'
}}>
<div style={{ fontSize: '14px', fontWeight: 'bold' }}>
{props.Item}
</div>
<div style={{ fontSize: '12px' }}>
${props.Sales}
</div>
<div style={{
fontSize: '11px',
color: isGrowing ? '#90EE90' : '#FFB6C6'
}}>
{props.Growth}
</div>
</div>
);
};
return (
<TreeMapComponent
dataSource={data}
leafItemSettings={{
labelTemplate: labelTemplate
}}
/>
);
}Text Wrapping & Overflow
Control how labels handle overflow in small rectangles:
Word Wrapping
<TreeMapComponent
dataSource={data}
leafItemSettings={{
labelPath: 'Item',
interSectAction: 'WrapByWord' // Wrap text to next line
}}
/>Wrapping Options
| Option | Behavior |
|---|---|
None | No wrapping, may overflow |
WrapByWord | Wrap to next line at word boundaries |
Wrap | Wrap at any character |
Trim | Truncate with ellipsis (...) |
Handling Small Rectangles
<TreeMapComponent
dataSource={data}
leafItemSettings={{
labelFormat: '${Item}: ${Value}',
interSectAction: 'WrapByWord', // Wrap if too long
labelFontStyle: {
size: '12px'
}
}}
/>Border and Fill Customization
Customize appearance of leaf items:
Individual Item Styling
const data = [
{ Item: 'A', Value: 100, Color: '#FF6B6B', BorderColor: '#333' },
{ Item: 'B', Value: 200, Color: '#4ECDC4', BorderColor: '#333' }
];
<TreeMapComponent
dataSource={data}
leafItemSettings={{
labelPath: 'Item',
fill: '#default_color',
border: {
color: '#border_default',
width: 1
}
}}
/>Border Configuration
<TreeMapComponent
dataSource={data}
leafItemSettings={{
labelPath: 'Item',
border: {
color: '#333', // Border color
width: 2, // Border width in pixels
}
}}
/>Gradient Borders for Hierarchy Levels
import { LevelsDirective, LevelDirective } from '@syncfusion/ej2-react-treemap';
<TreeMapComponent
dataSource={hierarchicalData}
>
<LevelsDirective>
<LevelDirective
groupPath="Category"
border={{ color: '#999', width: 1 }}
/>
<LevelDirective
groupPath="Type"
border={{ color: '#CCC', width: 0.5 }}
/>
</LevelsDirective>
</TreeMapComponent>Advanced Customization
Pattern 1: Size-Responsive Font
Adjust font size based on rectangle size:
export function ResponsiveFontSize() {
const labelTemplate = (props) => {
// Larger rectangles get larger fonts
const fontSize = props.value > 3000 ? '16px' : '12px';
return (
<div style={{ fontSize }}>
{props.label}
</div>
);
};
return (
<TreeMapComponent
dataSource={data}
leafItemSettings={{
labelTemplate: labelTemplate
}}
/>
);
}Pattern 2: Highlight Important Items
export function HighlightImportantItems() {
const labelTemplate = (props) => {
const isImportant = props.value > 5000;
return (
<div style={{
fontWeight: isImportant ? 'bold' : 'normal',
fontSize: isImportant ? '14px' : '12px',
color: isImportant ? '#FFF' : '#333'
}}>
{props.label}
</div>
);
};
return (
<TreeMapComponent
dataSource={data}
leafItemSettings={{
labelTemplate: labelTemplate
}}
/>
);
}Pattern 3: Icon-Based Labels
export function IconLabels() {
const categoryIcons = {
'Electronics': '📱',
'Clothing': '👕',
'Books': '📖',
'Furniture': '🪑'
};
const labelTemplate = (props) => {
const icon = categoryIcons[props.Category] || '📦';
return (
<div style={{ textAlign: 'center' }}>
<div style={{ fontSize: '20px' }}>{icon}</div>
<div style={{ fontSize: '11px' }}>
{props.Category}
</div>
</div>
);
};
return (
<TreeMapComponent
dataSource={data}
leafItemSettings={{
labelTemplate: labelTemplate
}}
/>
);
}Pattern 4: Percentage Display
export function PercentageLabels() {
const totalValue = data.reduce((sum, item) => sum + item.value, 0);
const labelTemplate = (props) => {
const percentage = ((props.value / totalValue) * 100).toFixed(1);
return (
<div style={{ textAlign: 'center' }}>
<div style={{ fontSize: '14px', fontWeight: 'bold' }}>
{percentage}%
</div>
<div style={{ fontSize: '10px' }}>
{props.label}
</div>
</div>
);
};
return (
<TreeMapComponent
dataSource={data}
leafItemSettings={{
labelTemplate: labelTemplate
}}
/>
);
}Best Practices
1. Label Position: Center for balanced items, corners for wide/tall items 2. Font Size: 12-14px for best readability 3. Multi-Line: Use newlines (\n) for complex labels 4. Overflow: Use WrapByWord for longer text 5. Hierarchy: Different borders for different levels 6. Accessibility: Ensure contrast between text and background
Common Issues
Issue: Labels not visible
- Solution: Check labelPath property matches data, verify font color vs background
Issue: Text overlaps in small rectangles
- Solution: Use
interSectAction: 'WrapByWord'or reduce font size
Issue: Template not rendering
- Solution: Ensure labelTemplate function returns valid React element
Next Steps
- Color Mapping: See color-mapping.md to color items by value
- Legends: See legends-tooltips-selection.md for legend integration
- Drill-Down: See drilldown.md for hierarchical navigation
Legends, Tooltips & Selection
Table of Contents
- Legend Configuration
- Basic Legend Setup
- Legend Positions
- Legend Customization
- Tooltip Customization
- Basic Tooltip Setup
- Tooltip Formats
- Tooltip Styling
- Template-Based Tooltips
- Selection and Highlight
- Enable Selection
- Selection Modes
- Selection Types
- Highlight (Hover) Effect
- Interactive Features
- Combined Selection and Highlight
- Synchronized Legend and Selection
- Event Handling
- Item Selected Event
- Item Highlighted Event
- Item Click Event
- Advanced Interactions
- Pattern 1: Click to Focus on Category
- Pattern 2: Show Details on Selection
- Pattern 3: Conditional Highlighting by Criteria
- Pattern 4: Cross-Filter with Legend
- Best Practices
- Common Issues
- Next Steps
Legend Configuration
Legends display item categories or ranges to help users interpret the TreeMap.
Basic Legend Setup
import { TreeMapComponent, Inject } from '@syncfusion/ej2-react-treemap';
import { TreeMapLegend } from '@syncfusion/ej2-react-treemap';
const data = [
{ Car: 'Mustang', Brand: 'Ford', Count: 232 },
{ Car: 'Swift', Brand: 'Maruti', Count: 143 },
{ Car: 'A3 Cabriolet', Brand: 'Audi', Count: 123 }
];
<TreeMapComponent
dataSource={data}
equalColorValuePath="Brand"
leafItemSettings={{
colorMapping: [
{ value: 'Ford', color: '#3498DB' },
{ value: 'Maruti', color: '#E74C3C' },
{ value: 'Audi', color: '#2ECC71' }
]
}}
legendSettings={{
visible: true,
position: 'Bottom'
}}
>
<Inject services={[TreeMapLegend]} />
</TreeMapComponent>Legend Positions
// Top position
legendSettings={{ visible: true, position: 'Top' }}
// Bottom position (default for most charts)
legendSettings={{ visible: true, position: 'Bottom' }}
// Left position
legendSettings={{ visible: true, position: 'Left' }}
// Right position
legendSettings={{ visible: true, position: 'Right' }}Legend Customization
<TreeMapComponent
legendSettings={{
visible: true,
position: 'Right',
height: '200px',
width: '200px',
labelDisplayMode: 'Trim', // Truncate long labels
title: {text: 'Brands'}
}}
/>Tooltip Customization
Tooltips display detailed information when hovering over items.
Basic Tooltip Setup
import { TreeMapTooltip } from '@syncfusion/ej2-react-treemap';
<TreeMapComponent
dataSource={data}
tooltipSettings={{
visible: true,
format: '${Item}: ${Value} units'
}}
>
<Inject services={[TreeMapTooltip]} />
</TreeMapComponent>Tooltip Formats
// Simple format
tooltipSettings={{
visible: true,
format: '${Item}'
}}
// Multi-line format
tooltipSettings={{
visible: true,
format: '${Item}\nValue: ${Value}\nCategory: ${Category}'
}}
// With labels
tooltipSettings={{
visible: true,
format: 'Item: ${Item}<br>Sales: ${Sales}<br>Region: ${Region}'
}}Tooltip Styling
tooltipSettings={{
visible: true,
format: '${Item}: ${Value}',
textStyle: {
fontFamily: 'Arial',
fontSize: '12px',
color: '#FFFFFF'
},
borderStyle: {
color: '#333',
width: 1
},
backgroundColor: '#000000'
}}Template-Based Tooltips
export function TemplateTooltip() {
const tooltipTemplate = (props) => {
return (
<div style={{
padding: '10px',
backgroundColor: '#f0f0f0',
borderRadius: '4px'
}}>
<div style={{ fontWeight: 'bold' }}>
{props.Item}
</div>
<div>
Sales: ${props.Value}
</div>
<div style={{ fontSize: '12px', color: '#666' }}>
{props.Category}
</div>
</div>
);
};
return (
<TreeMapComponent
dataSource={data}
tooltipSettings={{
visible: true,
template: tooltipTemplate
}}
>
<Inject services={[TreeMapTooltip]} />
</TreeMapComponent>
);
}Selection and Highlight
Allow users to select and highlight TreeMap items.
Enable Selection
import { TreeMapSelection } from '@syncfusion/ej2-react-treemap';
<TreeMapComponent
dataSource={data}
selectionSettings={{
mode: 'Item', // Select individual items
fill: '#FF6B6B', // Selection fill color
border: {
color: '#333',
width: 2
}
}}
>
<Inject services={[TreeMapSelection]} />
</TreeMapComponent>Selection Modes
| Mode | Behavior |
|---|---|
Item | Click item to select |
Parent | Click parent to select all children |
Group | Click to select related group |
Selection Types
// Single selection
selectionSettings={{ type: 'Single' }}
// Multiple selection
selectionSettings={{ type: 'Multiple' }}Highlight (Hover) Effect
import { TreeMapHighlight } from '@syncfusion/ej2-react-treemap';
<TreeMapComponent
dataSource={data}
highlightSettings={{
enable: true,
fill: '#FFD700', // Highlight color
border: {
color: '#333',
width: 2
},
opacity: '0.8'
}}
>
<Inject services={[TreeMapHighlight]} />
</TreeMapComponent>Interactive Features
Combined Selection and Highlight
export function InteractiveTreeMap() {
return (
<TreeMapComponent
dataSource={data}
selectionSettings={{
mode: 'Item',
fill: '#4ECDC4'
}}
highlightSettings={{
enable: true,
fill: '#FFD700',
opacity: '0.7'
}}
legendSettings={{
visible: true,
position: 'Right'
}}
tooltipSettings={{
visible: true,
format: '${Item}: ${Value}'
}}
>
<Inject services={[
TreeMapSelection,
TreeMapHighlight,
TreeMapLegend,
TreeMapTooltip
]} />
</TreeMapComponent>
);
}Synchronized Legend and Selection
export function SynchronizedSelection() {
const [selectedBrand, setSelectedBrand] = React.useState(null);
const handleItemSelected = (args) => {
const brand = args.item?.Brand;
setSelectedBrand(brand);
};
return (
<TreeMapComponent
dataSource={data}
equalColorValuePath="Brand"
onItemSelected={handleItemSelected}
selectionSettings={{
mode: 'Item',
type: 'Multiple',
fill: '#FF6B6B'
}}
legendSettings={{
visible: true
}}
>
<Inject services={[TreeMapSelection, TreeMapLegend]} />
</TreeMapComponent>
);
}Event Handling
Item Selected Event
export function HandleItemSelection() {
const handleItemSelected = (args) => {
console.log('Selected item:', args.item);
console.log('Index:', args.itemIndex);
// Update external state or trigger action
};
return (
<TreeMapComponent
dataSource={data}
onItemSelected={handleItemSelected}
selectionSettings={{
enable: true
}}
>
<Inject services={[TreeMapSelection]} />
</TreeMapComponent>
);
}Item Highlighted Event
export function HandleItemHighlight() {
const handleItemHighlight = (args) => {
console.log('Highlighted item:', args.item?.label);
// Could use to show details panel
};
return (
<TreeMapComponent
dataSource={data}
onItemHighlight={handleItemHighlight}
highlightSettings={{
enable: true,
fill: '#FFD700'
}}
>
<Inject services={[TreeMapHighlight]} />
</TreeMapComponent>
);
}Item Click Event
export function HandleItemClick() {
const [clickedItem, setClickedItem] = React.useState(null);
const handleItemClick = (args) => {
setClickedItem({
label: args.item?.label,
value: args.item?.value,
timestamp: new Date()
});
};
return (
<div>
<TreeMapComponent
dataSource={data}
onItemClick={handleItemClick}
/>
{clickedItem && (
<div>
Last clicked: {clickedItem.label} ({clickedItem.value})
</div>
)}
</div>
);
}Advanced Interactions
Pattern 1: Click to Focus on Category
export function FocusOnCategory() {
const [focusCategory, setFocusCategory] = React.useState(null);
const treeMapRef = React.useRef(null);
const handleItemClick = (args) => {
const category = args.item?.Brand;
setFocusCategory(category);
// Highlight only items from selected category
const filtered = data.filter(item => item.Brand === category);
};
return (
<TreeMapComponent
ref={treeMapRef}
dataSource={data}
onItemClick={handleItemClick}
selectionSettings={{
enable: true
}}
>
<Inject services={[TreeMapSelection]} />
</TreeMapComponent>
);
}Pattern 2: Show Details on Selection
export function ShowDetailsPanel() {
const [selectedItem, setSelectedItem] = React.useState(null);
const handleItemSelected = (args) => {
setSelectedItem({
name: args.item?.label,
value: args.item?.value,
category: args.item?.Brand,
details: args.item__
});
};
return (
<div style={{ display: 'grid', gridTemplateColumns: '2fr 1fr', gap: '20px' }}>
<TreeMapComponent
dataSource={data}
onItemSelected={handleItemSelected}
selectionSettings={{ enable: true }}
>
<Inject services={[TreeMapSelection]} />
</TreeMapComponent>
{selectedItem && (
<div style={{
padding: '20px',
border: '1px solid #ccc',
borderRadius: '4px'
}}>
<h3>{selectedItem.name}</h3>
<p>Value: {selectedItem.value}</p>
<p>Category: {selectedItem.category}</p>
</div>
)}
</div>
);
}Pattern 3: Conditional Highlighting by Criteria
export function ConditionalHighlight() {
const handleItemHighlight = (args) => {
const value = args.item?.value;
// Change highlight color based on value
if (value > 5000) {
args.highlightSettings.fill = '#27AE60'; // Green for high
} else if (value > 2000) {
args.highlightSettings.fill = '#F39C12'; // Orange for medium
} else {
args.highlightSettings.fill = '#E74C3C'; // Red for low
}
};
return (
<TreeMapComponent
dataSource={data}
onItemHighlight={handleItemHighlight}
highlightSettings={{ enable: true }}
>
<Inject services={[TreeMapHighlight]} />
</TreeMapComponent>
);
}Pattern 4: Cross-Filter with Legend
export function CrossFilterWithLegend() {
const filteredData = selectedBrands.size === 0
? data
: data.filter(item => selectedBrands.has(item.Brand));
return (
<TreeMapComponent
dataSource={filteredData}
legendSettings={{
visible: true,
mode: 'Interactive' // Click legend to filter
}}
>
<Inject services={[TreeMapLegend]} />
</TreeMapComponent>
);
}Best Practices
1. Legends: Always include legends when using color mapping 2. Tooltips: Provide detailed information on hover 3. Selection: Clear visual feedback when items selected 4. Highlight: Subtle highlight effect to guide users 5. Mobile: Ensure interactions work on touch devices 6. Accessibility: Provide keyboard navigation alternatives
Common Issues
Issue: Legend not showing
- Solution: Ensure TreeMapLegend service injected and legendSettings.visible = true
Issue: Tooltip not appearing
- Solution: Check TreeMapTooltip service injected, verify format property
Issue: Selection not working
- Solution: Inject TreeMapSelection service, verify selectionSettings configured
Next Steps
- Drill-Down: See drilldown.md for hierarchical navigation
- Color Mapping: See color-mapping.md for visual strategies
- Customization: See customization-accessibility.md for advanced styling