
Syncfusion React Sankey
- 385 installs
- 3 repo stars
- Updated July 28, 2026
- syncfusion/react-ui-components-skills
Use syncfusion-react-sankey for development tasks
About
syncfusion-react-sankey: A skill for development. This provides functionality for development workflows.
- syncfusion-react-sankey
Syncfusion React Sankey by the numbers
- 385 all-time installs (skills.sh)
- +52 installs in the week ending Aug 5, 2026 (Skillselion tracking)
- Ranked #1,129 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-sankeyAdd your badge
Show developers this skill is listed on Skillselion. Paste this into your README.
| Installs | 385 |
|---|---|
| repo stars | ★ 3 |
| Last updated | July 28, 2026 |
| Repository | syncfusion/react-ui-components-skills ↗ |
What it does
Use syncfusion-react-sankey for development tasks
Files
Implementing Syncfusion React Sankey Chart
When to Use This Skill
Use this skill when you need to:
- Display energy flows or process dependencies
- Visualize hierarchical relationships and data movement between categories
- Create interactive node-link diagrams with custom styling
- Build responsive flow visualizations with legends and tooltips
- Enable user interactions like clicks and hover effects
- Export or print flow diagrams
- Support accessibility features and RTL layouts
Component Overview
The Syncfusion React Sankey Chart component visualizes flow data through interconnected nodes and links, perfect for displaying energy consumption, data flows, process hierarchies, and organizational relationships. It provides rich customization options for appearance, interactivity, and accessibility.
Key Features:
- Node & Link Configuration - Define data sources and destinations with custom styling
- Labels & Positioning - Control text display, node positioning, and title/subtitle
- Legend Support - Display legend with customizable positioning and styling
- Interactivity - Tooltips, click events, and user interactions
- Appearance Customization - Colors, opacity, link curvature, and theming
- RTL Support - Right-to-left layout for international applications
- Accessibility - WCAG compliance and screen reader support
- Export Capabilities - Export diagrams and print functionality
Documentation and Navigation Guide
Getting Started
📄 Read: references/getting-started.md
- Installation and package setup
- Dependencies and module injection
- Basic Sankey component creation
- Development environment setup
- Running your first example
Nodes and Links Configuration
📄 Read: references/nodes-and-links.md
- Node structure and properties
- Link structure and data flow
- Data binding and source/target relationships
- Node positioning with offset property
- Link styling and customization
- Performance optimization for large datasets
Labels and Positioning
📄 Read: references/labels-and-positioning.md
- Label visibility and configuration
- Node label positioning and alignment
- Title and subtitle settings
- Text formatting and styling options
- Handling label overflow scenarios
Legend and Display Options
📄 Read: references/legend-and-display.md
- Legend configuration and visibility
- Legend positioning (Top, Bottom, Left, Right)
- Display options and item padding
- Visual styling and theming
- Color customization
Interactivity and Events
📄 Read: references/interactivity.md
- Tooltip configuration and display
- Event handling (nodeClick, linkClick, load events)
- User interaction patterns
- Enabling/disabling interactive features
- Event callbacks and data access
Appearance and Styling
📄 Read: references/appearance-and-styling.md
- Link styling (opacity, curvature, colorType)
- Node appearance customization
- Color schemes and theming
- CSS integration and custom styling
- Responsive design considerations
Accessibility and Orientation
📄 Read: references/accessibility-and-orientation.md
- RTL (Right-to-Left) layout support
- WCAG accessibility compliance
- Keyboard navigation support
- Screen reader compatibility
- Device responsiveness
Export and Print Features
📄 Read: references/export-and-print.md
- Export functionality and image formats
- Print capabilities
- Exporting diagram data
- Configuration options
- Common export scenarios
API Reference
📄 Read: references/sankey-props.md • references/sankey-events.md • references/sankey-methods.md • references/sankey-examples.md
- Machine-parsable API listings for component props, events, and methods
- Verified defaults, types, and short descriptions mapped from Syncfusion React Sankey API
- Implementation examples illustrating common patterns and method usage
Quick Start Example
import React from 'react';
import {
SankeyComponent, Inject, SankeyTooltip, SankeyLegend, SankeyExport,
SankeyNodeDirective,
SankeyNodesCollectionDirective,
SankeyLinkDirective,
SankeyLinksCollectionDirective
} from '@syncfusion/ej2-react-charts';
import * as ReactDOM from "react-dom";
function BasicSankey() {
return (
<div className="control-pane">
<div className="control-section">
<SankeyComponent
width="90%"
height="420px"
title="Energy Flow"
tooltip={{ enable: true }}
legendSettings={{ visible: true, position: 'Bottom' }}
>
<SankeyNodesCollectionDirective>
<SankeyNodeDirective id="Solar" label={{ text: 'Solar' }} />
<SankeyNodeDirective id="Generation" label={{ text: 'Generation' }} />
<SankeyNodeDirective id="Consumption" label={{ text: 'Consumption' }} />
</SankeyNodesCollectionDirective>
<SankeyLinksCollectionDirective>
<SankeyLinkDirective sourceId="Solar" targetId="Generation" value={450} />
<SankeyLinkDirective sourceId="Generation" targetId="Consumption" value={400} />
</SankeyLinksCollectionDirective>
<Inject services={[SankeyTooltip, SankeyLegend, SankeyExport]} />
</SankeyComponent>
</div>
</div>
);
}
export default BasicSankey;
ReactDOM.render(<BasicSankey />, document.getElementById("charts"));Common Patterns
Pattern 1: Multi-Level Flow Visualization
Create hierarchical flows with multiple source and destination nodes for complex data relationships.
<SankeyComponent title="Process Flow">
<SankeyNodesCollectionDirective>
<SankeyNodeDirective id="Input" />
<SankeyNodeDirective id="Processing" />
<SankeyNodeDirective id="Output" />
</SankeyNodesCollectionDirective>
<SankeyLinksCollectionDirective>
<SankeyLinkDirective sourceId="Input" targetId="Processing" value={100} />
<SankeyLinkDirective sourceId="Processing" targetId="Output" value={80} />
</SankeyLinksCollectionDirective>
<Inject services={[SankeyTooltip, SankeyLegend]} />
</SankeyComponent>Pattern 2: Styled Links with Color Types
Customize link appearance using colorType to inherit colors from source or apply custom styling.
<SankeyComponent
linkStyle={{
opacity: 0.6,
curvature: 0.55,
colorType: 'Source'
}}
>
{/* nodes and links */}
<Inject services={[SankeyTooltip, SankeyLegend]} />
</SankeyComponent>Pattern 3: Responsive with Device Detection
Adapt component dimensions and display based on device type for better UX.
import { Browser } from '@syncfusion/ej2-base';
<SankeyComponent
height={Browser.isDevice ? '600px' : '450px'}
labelSettings={{ visible: !Browser.isDevice }}
>
{/* nodes and links */}
<Inject services={[SankeyTooltip, SankeyLegend]} />
</SankeyComponent>Key Props Reference
| Prop | Type | Purpose |
|---|---|---|
width | string | Chart width (e.g., '90%', '800px') |
height | string | Chart height (e.g., '420px') |
title | string | Main chart title |
subTitle | string | Chart subtitle |
tooltip | object | Tooltip configuration |
legendSettings | object | Legend visibility and positioning |
labelSettings | object | Node label configuration |
linkStyle | object | Link styling (opacity, curvature, colorType) |
Common Use Cases
1. Energy Consumption Flow - Track energy from sources through generation, distribution, to consumption sectors 2. Process Dependencies - Visualize workflow stages and data movement through processes 3. Organizational Hierarchy - Display reporting structures and resource allocation 4. Supply Chain Flow - Show product movement from suppliers through manufacturing to distribution 5. Data Pipeline - Visualize data transformation and routing through system components
---
Accessibility and Orientation
Table of Contents
- RTL (Right-to-Left) Support
- Enabling RTL
- RTL with Dynamic Language
- RTL Layout Considerations
- WCAG Accessibility Compliance
- Semantic Structure
- Color Contrast
- Keyboard Navigation
- Alt Text and Descriptions
- Screen Reader Support
- ARIA Labels
- Screen Reader Friendly Tooltips
- Responsive Design
- Mobile Accessibility
- Touch-Friendly Interactions
- Focus Management
- Visible Focus Indicators
- Complete Accessible Example
- Best Practices
RTL (Right-to-Left) Support
Support international applications with RTL layout for languages like Arabic, Hebrew, and Persian.
Enabling RTL
<SankeyComponent
width="90%"
height="420px"
title="مخطط سانكي"
enableRtl={true}
>
{/* nodes and links */}
<Inject services={[SankeyTooltip, SankeyLegend]} />
</SankeyComponent>RTL with Dynamic Language
import React, { useState } from 'react';
import {
SankeyComponent, Inject, SankeyTooltip, SankeyLegend, SankeyExport,
SankeyNodeDirective,
SankeyNodesCollectionDirective,
SankeyLinkDirective,
SankeyLinksCollectionDirective
} from '@syncfusion/ej2-react-charts';
import * as ReactDOM from "react-dom";
function MultiLanguageSankey() {
const [language, setLanguage] = useState('en');
const translations = {
en: {
title: 'Energy Flow',
solar: 'Solar',
wind: 'Wind',
output: 'Output'
},
ar: {
title: 'تدفق الطاقة',
solar: 'الطاقة الشمسية',
wind: 'الرياح',
output: 'الإنتاج'
}
};
const currentTranslation = translations[language];
const isRTL = language === 'ar';
return (
<div dir={isRTL ? 'rtl' : 'ltr'}>
<select onChange={(e) => setLanguage(e.target.value)}>
<option value="en">English</option>
<option value="ar">العربية</option>
</select>
<SankeyComponent
width="90%"
height="420px"
title={currentTranslation.title}
enableRtl={isRTL}
>
<SankeyNodesCollectionDirective>
<SankeyNodeDirective
id="Solar"
label={{ text: currentTranslation.solar }}
/>
<SankeyNodeDirective
id="Wind"
label={{ text: currentTranslation.wind }}
/>
<SankeyNodeDirective
id="Output"
label={{ text: currentTranslation.output }}
/>
</SankeyNodesCollectionDirective>
<SankeyLinksCollectionDirective>
<SankeyLinkDirective sourceId="Solar" targetId="Output" value={100} />
<SankeyLinkDirective sourceId="Wind" targetId="Output" value={80} />
</SankeyLinksCollectionDirective>
<Inject services={[SankeyTooltip, SankeyLegend]} />
</SankeyComponent>
</div>
);
}
export default MultiLanguageSankey;
ReactDOM.render(<MultiLanguageSankey />, document.getElementById("charts"));RTL Layout Considerations
When enabling RTL:
- Legend positioning adapts automatically
- Node labels align right
- Links flow from right to left
- Navigation direction reverses
<SankeyComponent
width="90%"
height="420px"
enableRtl={true}
legendSettings={{
visible: true,
position: 'Bottom' // Automatically adapted for RTL
}}
labelSettings={{
visible: true
// Text alignment handled automatically
}}
>
{/* nodes and links */}
</SankeyComponent>WCAG Accessibility Compliance
Ensure your Sankey diagram meets Web Content Accessibility Guidelines (WCAG) 2.1 standards.
WCAG Level AA Compliance
1. Semantic Structure
Use proper HTML markup:
<section aria-label="Energy Flow Sankey Diagram">
<h2>Energy Consumption 2024</h2>
<SankeyComponent
width="90%"
height="420px"
role="img"
aria-label="Sankey chart showing energy flow from sources to consumption sectors"
>
{/* nodes and links */}
</SankeyComponent>
<p>Chart description for screen readers</p>
</section>2. Color Contrast
Ensure sufficient color contrast ratios:
// WCAG AA requires 4.5:1 contrast ratio for normal text
// WCAG AAA requires 7:1 ratio
const accessibleColors = {
darkBlue: '#003366', // High contrast
lightText: '#FFFFFF', // 21:1 ratio with dark blue
darkText: '#000000', // Maximum contrast
mediumGray: '#666666',
lightGray: '#CCCCCC'
};
<SankeyComponent
linkStyle={{
opacity: 0.7 // Higher opacity for better visibility
}}
>
<SankeyNodesCollectionDirective>
<SankeyNodeDirective
id="A"
color={accessibleColors.darkBlue}
label={{
fill: accessibleColors.lightText
}}
/>
</SankeyNodesCollectionDirective>
</SankeyComponent>3. Keyboard Navigation
Enable keyboard access:
We do not expose a dedicated API like allowKeyboardInteraction for keyboard navigation. The desired navigation behavior is achieved through standard Tab and arrow key actions.
| Press | To do this |
|---|---|
| Alt + J | Moves the focus to the Sankey Chart element. |
| Tab | Moves the focus to the next element in the chart. |
| Shift + Tab | Moves the focus to the previous element in the chart. |
| Down Arrow | Moves the focus to the node or link below the selected element. |
| Up Arrow | Moves the focus to the node or link above the selected element. |
| Left Arrow | Moves the focus to the next node or link from the selected element. |
| Right Arrow | Moves the focus to the previous node or link from the selected element. |
| ESC | Cancels the tooltip for the node or link. |
| Ctrl + P | Prints the Sankey Chart. |
function AccessibleSankey() {
return (
<div>
<SankeyComponent
width="90%"
height="420px"
title="Keyboard Navigable Sankey"
>
{/* nodes and links */}
</SankeyComponent>
</div>
);
}
export default AccessibleSankey;4. Alt Text and Descriptions
Provide text alternatives:
<figure>
<SankeyComponent
width="90%"
height="420px"
title="Energy Flow Analysis"
role="img"
aria-label="Sankey diagram depicting energy sources (Solar, Wind, Gas) flowing to consumption sectors (Residential, Commercial, Industrial)"
>
{/* nodes and links */}
</SankeyComponent>
<figcaption>
Energy distribution showing 450 units from Solar, 200 from Wind,
and 800 from Natural Gas, distributed among residential (300),
commercial (400), and industrial (350) sectors.
</figcaption>
</figure>Screen Reader Support
ARIA Labels
<SankeyComponent
aria-label="Energy consumption Sankey diagram"
role="img"
>
<SankeyNodesCollectionDirective>
<SankeyNodeDirective
id="Solar"
aria-label="Solar energy source"
label={{ text: 'Solar' }}
/>
</SankeyNodesCollectionDirective>
<Inject services={[SankeyTooltip, SankeyLegend]} />
</SankeyComponent>Screen Reader Friendly Tooltips
<SankeyComponent
tooltip={{
enable: true,
template: `
<div role="tooltip">
<span aria-live="polite">
Flow from {source} to {target}: {value} units
</span>
</div>
`
}}
>
{/* nodes and links */}
</SankeyComponent>Responsive Design
Mobile Accessibility
import { Browser } from '@syncfusion/ej2-base';
<SankeyComponent
width={Browser.isDevice ? '100%' : '90%'}
height={Browser.isDevice ? '700px' : '500px'}
labelSettings={{
visible: !Browser.isDevice, // Hide labels on mobile
fontSize: Browser.isDevice ? 10 : 12
}}
tooltip={{
enable: true // Rely on tooltips for mobile info
}}
legendSettings={{
visible: true,
position: Browser.isDevice ? 'Bottom' : 'Right',
itemPadding: Browser.isDevice ? 4 : 8
}}
>
{/* nodes and links */}
</SankeyComponent>Touch-Friendly Interactions
function TouchAccessibleSankey() {
const [selectedNode, setSelectedNode] = React.useState(null);
const onNodeClick = (args) => {
// Works for both mouse click and touch
setSelectedNode(args.data.id);
};
return (
<div>
<SankeyComponent
width="100%"
height="600px"
nodeClick={onNodeClick}
>
{/* nodes and links */}
</SankeyComponent>
{selectedNode && (
<div
role="region"
aria-live="polite"
aria-label={`Information for ${selectedNode}`}
>
<h3>Selected: {selectedNode}</h3>
{/* Details about selected node */}
</div>
)}
</div>
);
}
export default TouchAccessibleSankey;Focus Management
Visible Focus Indicators
<div style={{
outline: 'none'
}}>
<SankeyComponent
width="90%"
height="420px"
title="Focusable Chart"
tabIndex={0}
style={{
outline: '3px solid #0066CC',
outlineOffset: '2px'
}}
>
{/* nodes and links */}
</SankeyComponent>
</div>
<style>{`
.sankey-chart:focus {
outline: 3px solid #0066CC;
outline-offset: 2px;
}
`}</style>Complete Accessible Example
import React from 'react';
import { Browser } from '@syncfusion/ej2-base';
import {
SankeyComponent,
Inject,
SankeyTooltip,
SankeyLegend,
SankeyExport,
SankeyNodeDirective,
SankeyNodesCollectionDirective,
SankeyLinkDirective,
SankeyLinksCollectionDirective,
} from '@syncfusion/ej2-react-charts';
import * as ReactDOM from 'react-dom';
function FullyAccessibleSankey() {
return (
<SankeyComponent
id="sankey-container"
width="90%"
height={Browser.isDevice ? '600' : '450'}
title="California Energy Consumption in 2023"
subTitle="Source: Lawrence Livermore National Laboratory"
linkStyle={{ opacity: 0.6, curvature: 0.55, colorType: 'Source' }}
labelSettings={{ visible: true }}
tooltip={{ enable: true }}
legendSettings={{ visible: true }}
>
<Inject services={[SankeyTooltip, SankeyLegend, SankeyExport]} />
<SankeyNodesCollectionDirective>
<SankeyNodeDirective id="Solar" label={{ text: 'Solar' }} />
<SankeyNodeDirective id="Generation" label={{ text: 'Generation' }} />
<SankeyNodeDirective id="Consumption" label={{ text: 'Consumption' }} />
</SankeyNodesCollectionDirective>
<SankeyLinksCollectionDirective>
<SankeyLinkDirective
sourceId="Solar"
targetId="Generation"
value={450}
/>
<SankeyLinkDirective
sourceId="Generation"
targetId="Consumption"
value={400}
/>
</SankeyLinksCollectionDirective>
</SankeyComponent>
);
}
export default FullyAccessibleSankey;
ReactDOM.render(<FullyAccessibleSankey />, document.getElementById('charts'));Best Practices
1. Test with screen readers - Use NVDA, JAWS, or VoiceOver 2. Keyboard navigation - Support all interactions via keyboard 3. Color alone - Never use color as only means of conveying info 4. Focus visible - Always show focus indicators 5. ARIA labels - Provide context for dynamic content 6. Text alternatives - Include data tables or descriptions 7. Mobile first - Design for touch and small screens 8. Regular audits - Test accessibility regularly
Appearance and Styling
Table of Contents
- Link Styling
- Link Style Properties
- Basic Link Styling Example
- Opacity Variations
- Curvature Variations
- Color Type Strategies
- Source Color (Default)
- Target Color
- Node Appearance
- Node Color Assignment
- Node Label Styling
- Theme Customization
- Color Schemes
- Professional Color Palette
- Energy Sector Color Scheme
- Heat Map Color Scheme
- Theming
- Chart Background and Borders
- Text Styling (Titles and Labels)
- Responsive Styling
- Adaptive Sizing
- Dark Mode Support
- Best Practices
Link Styling
Customize how links (connections between nodes) appear in your diagram.
Link Style Properties
<SankeyComponent
linkStyle={{
opacity: 0.6, // Transparency: 0 (invisible) to 1 (opaque)
curvature: 0.55, // Curve intensity: 0 (straight) to 1 (highly curved)
colorType: 'Source' // Color inheritance: 'Source' or 'Target'
}}
>
{/* nodes and links */}
</SankeyComponent>Basic Link Styling Example
<SankeyComponent
title="Styled Links"
linkStyle={{
opacity: 0.5,
curvature: 0.6,
colorType: 'Source'
}}
>
<SankeyNodesCollectionDirective>
<SankeyNodeDirective id="A" color="#FF6B6B" />
<SankeyNodeDirective id="B" color="#4ECDC4" />
<SankeyNodeDirective id="C" color="#45B7D1" />
</SankeyNodesCollectionDirective>
<SankeyLinksCollectionDirective>
<SankeyLinkDirective sourceId="A" targetId="C" value={100} />
<SankeyLinkDirective sourceId="B" targetId="C" value={75} />
</SankeyLinksCollectionDirective>
<Inject services={[SankeyTooltip, SankeyLegend]} />
</SankeyComponent>Opacity Variations
Control transparency for different visual effects:
| Opacity | Effect | Use Case |
|---|---|---|
| 0.3 | Very transparent | Background flows, less important data |
| 0.5 | Semi-transparent | Standard visualization |
| 0.7 | Mostly opaque | Emphasized flows |
| 1.0 | Fully opaque | Critical data, high contrast |
<SankeyComponent
title="Opacity Levels"
linkStyle={{
opacity: 0.6, // Start with 0.6
curvature: 0.55
}}
>
{/* nodes and links */}
</SankeyComponent>Curvature Variations
Adjust link curves for different visual preferences:
| Curvature | Shape | Best For |
|---|---|---|
| 0 | Straight lines | Linear flows, simple diagrams |
| 0.3 | Slight curves | Moderate complexity |
| 0.55 | Medium curves | Balanced appearance (default) |
| 0.8 | Heavy curves | Dense diagrams, clarity |
| 1.0 | Maximum curves | Artistic effect |
<SankeyComponent
title="Different Curvatures"
>
<SankeyNodesCollectionDirective>
{/* nodes */}
</SankeyNodesCollectionDirective>
<SankeyLinksCollectionDirective>
{/* links */}
</SankeyLinksCollectionDirective>
</SankeyComponent>Color Type Strategies
Source Color (Default)
Links inherit color from their source node:
<SankeyComponent
linkStyle={{
colorType: 'Source'
}}
>
<SankeyNodesCollectionDirective>
<SankeyNodeDirective id="Solar" color="#FFD700" />
<SankeyNodeDirective id="Wind" color="#87CEEB" />
<SankeyNodeDirective id="Output" color="#C0C0C0" />
</SankeyNodesCollectionDirective>
<SankeyLinksCollectionDirective>
{/* Links from Solar appear gold, from Wind appear blue */}
<SankeyLinkDirective sourceId="Solar" targetId="Output" value={450} />
<SankeyLinkDirective sourceId="Wind" targetId="Output" value={200} />
</SankeyLinksCollectionDirective>
<Inject services={[SankeyTooltip]} />
</SankeyComponent>Target Color
Links inherit color from destination node:
<SankeyComponent
linkStyle={{
colorType: 'Target'
}}
>
{/* All links pointing to same destination get same color */}
</SankeyComponent>Node Appearance
Node Color Assignment
<SankeyNodesCollectionDirective>
<SankeyNodeDirective
id="Solar"
color="#FFD700" // Gold
label={{ text: 'Solar' }}
/>
<SankeyNodeDirective
id="Wind"
color="#87CEEB" // Sky blue
label={{ text: 'Wind' }}
/>
</SankeyNodesCollectionDirective>Node Label Styling
<SankeyNodeDirective
id="Node1"
label={{
text: 'Styled Label',
fill: '#333333', // Text color
fontSize: 12,
fontFamily: 'Arial',
textOpacity: 0.9
}}
/>Theme Customization
Available themes (18+ including dark & high contrast):
- Material, MaterialDark, Material3, Material3Dark
- Fabric, FabricDark
- Bootstrap, BootstrapDark, Bootstrap4, Bootstrap5, Bootstrap5Dark, Bootstrap5.3, Bootstrap5.3Dark
- Tailwind, TailwindDark
- Fluent, FluentDark, Fluent2, Fluent2Dark, Fluent2HighContrast
- HighContrast, HighContrastLight
Switch via the theme prop:
<SankeyComponent theme='Material3Dark'>
{/* Sankey content */}
</SankeyComponent>Color Schemes
Professional Color Palette
const professionalColors = {
primary: ['#0066CC', '#003399', '#003366'],
secondary: ['#FF6B6B', '#FF8787', '#FFB3B3'],
neutral: ['#666666', '#999999', '#CCCCCC']
};
<SankeyNodesCollectionDirective>
<SankeyNodeDirective id="A" color={professionalColors.primary[0]} />
<SankeyNodeDirective id="B" color={professionalColors.primary[1]} />
<SankeyNodeDirective id="C" color={professionalColors.secondary[0]} />
</SankeyNodesCollectionDirective>Energy Sector Color Scheme
const energyColors = {
renewable: {
solar: '#FFD700',
wind: '#87CEEB',
hydro: '#20B2AA'
},
fossil: {
coal: '#696969',
gas: '#FFA07A',
oil: '#8B4513'
},
output: {
residential: '#FF69B4',
commercial: '#00CED1',
industrial: '#9370DB'
}
};
<SankeyNodesCollectionDirective>
<SankeyNodeDirective id="Solar" color={energyColors.renewable.solar} />
<SankeyNodeDirective id="Wind" color={energyColors.renewable.wind} />
<SankeyNodeDirective id="Coal" color={energyColors.fossil.coal} />
<SankeyNodeDirective id="Residential" color={energyColors.output.residential} />
</SankeyNodesCollectionDirective>Heat Map Color Scheme
Use gradient colors to represent intensity:
function getColorForValue(value, min, max) {
const ratio = (value - min) / (max - min);
// Red (low) to Green (high)
if (ratio < 0.5) {
return '#FF6B6B'; // Red
} else if (ratio < 0.75) {
return '#FFD700'; // Yellow
} else {
return '#32CD32'; // Green
}
}
const minValue = 50;
const maxValue = 500;
<SankeyNodesCollectionDirective>
<SankeyNodeDirective
id="HighValue"
color={getColorForValue(450, minValue, maxValue)}
/>
<SankeyNodeDirective
id="LowValue"
color={getColorForValue(100, minValue, maxValue)}
/>
</SankeyNodesCollectionDirective>Theming
Chart Background and Borders
<SankeyComponent
width="90%"
height="420px"
title="Themed Chart"
background="#F5F5F5"
border={{
color: '#CCCCCC',
width: 1
}}
>
{/* nodes and links */}
</SankeyComponent>Text Styling (Titles and Labels)
<SankeyComponent
title="Styled Title"
subTitle="Styled Subtitle"
titleStyle={{
fontFamily: 'Segoe UI',
size: '16px',
bold: true,
color: '#2E3440'
}}
subTitleStyle={{
fontFamily: 'Segoe UI',
size: '12px',
color: '#555555'
}}
>
{/* nodes and links */}
</SankeyComponent>Responsive Styling
Adaptive Sizing
import { Browser } from '@syncfusion/ej2-base';
<SankeyComponent
width={Browser.isDevice ? '100%' : '90%'}
height={Browser.isDevice ? '600px' : '420px'}
labelSettings={{
fontSize: Browser.isDevice ? 10 : 12
}}
linkStyle={{
opacity: Browser.isDevice ? 0.7 : 0.6,
curvature: Browser.isDevice ? 0.7 : 0.55
}}
>
{/* nodes and links */}
</SankeyComponent>Dark Mode Support
import React, { useState } from 'react';
function ThemedSankey() {
const [isDarkMode, setIsDarkMode] = useState(false);
const themes = {
light: {
background: '#FFFFFF',
linkOpacity: 0.6,
linkColor: 'Source',
nodeColors: ['#FF6B6B', '#4ECDC4', '#45B7D1'],
textColor: '#333333'
},
dark: {
background: '#1E1E1E',
linkOpacity: 0.5,
linkColor: 'Source',
nodeColors: ['#FF7675', '#55EFC4', '#74B9FF'],
textColor: '#ECEFF4'
}
};
const theme = isDarkMode ? themes.dark : themes.light;
return (
<div>
<button onClick={() => setIsDarkMode(!isDarkMode)}>
Toggle Dark Mode
</button>
<SankeyComponent
background={theme.background}
linkStyle={{
opacity: theme.linkOpacity,
colorType: theme.linkColor
}}
>
<SankeyNodesCollectionDirective>
{theme.nodeColors.map((color, i) => (
<SankeyNodeDirective
key={i}
id={`Node${i}`}
color={color}
label={{
text: `Node ${i}`,
fill: theme.textColor
}}
/>
))}
</SankeyNodesCollectionDirective>
<Inject services={[SankeyTooltip, SankeyLegend]} />
</SankeyComponent>
</div>
);
}
export default ThemedSankey;Best Practices
1. Maintain contrast - Ensure text is readable against backgrounds 2. Use consistent colors - Related items should have similar hues 3. Limit palette - 5-8 colors maximum for clarity 4. Test on different devices - Verify styling on mobile/tablet 5. Accessibility first - Avoid color-only distinctions 6. Performance - Complex CSS can slow rendering 7. Responsive design - Adapt styling for different screen sizes 8. Meaningful colors - Use colors that convey semantic meaning
Export and Print Features
Table of Contents
- Export Functionality
- Enabling Export
- Export Methods
- Export with User Interface
- Export Formats
- PNG Export
- JPEG Export
- PDF Export
- SVG Export
- Export Configuration
- Custom Export Filename
- Export with Orientation
- Multiple Format Export
- Print Functionality
- Browser Print
- Print Configuration
- Complete Export Example
- Best Practices
Export Functionality
Export Sankey diagrams in various formats for sharing, documentation, or further processing.
Enabling Export
import {
SankeyComponent, Inject, SankeyExport,
SankeyNodeDirective, SankeyNodesCollectionDirective,
SankeyLinkDirective, SankeyLinksCollectionDirective
} from '@syncfusion/ej2-react-charts';
<SankeyComponent
width="90%"
height="420px"
title="Exportable Chart"
>
{/* nodes and links */}
<Inject services={[SankeyExport]} />
</SankeyComponent>Export Methods
// Export as PNG (raster image)
chartRef.current?.export('PNG', 'sankey.png');
// Export as JPEG
chartRef.current?.export('JPEG', 'sankey.jpg');
// Export as PDF
chartRef.current?.export('PDF', 'sankey.pdf');
// Export as SVG (vector image)
chartRef.current?.export('SVG', 'sankey.svg');Export with User Interface
Add export buttons to your component:
import React, { useRef } from 'react';
import { SankeyComponent, SankeyExport } from '@syncfusion/ej2-react-charts';
function ExportableSankey() {
const chartRef = useRef(null);
const exportChart = (format) => {
if (chartRef.current) {
const fileName = `sankey-diagram-${new Date().getTime()}.${format.toLowerCase()}`;
chartRef.current.export(format, fileName);
}
};
return (
<div>
<div style={{ marginBottom: '15px' }}>
<button onClick={() => exportChart('PNG')}>Export as PNG</button>
<button onClick={() => exportChart('PDF')}>Export as PDF</button>
<button onClick={() => exportChart('SVG')}>Export as SVG</button>
<button onClick={() => window.print()}>Print</button>
</div>
<SankeyComponent
ref={chartRef}
width="90%"
height="420px"
title="Energy Flow"
>
{/* nodes and links */}
<Inject services={[SankeyExport]} />
</SankeyComponent>
</div>
);
}
export default ExportableSankey;Export Formats
PNG Export
Portable Network Graphics - raster format, widely compatible.
const exportAsPNG = () => {
chartRef.current?.export('PNG', 'diagram.png');
};Characteristics:
- Lossless compression
- Transparent background support
- Good for web and email
- Fixed resolution
JPEG Export
Compressed raster format, smaller file size.
const exportAsJPEG = () => {
chartRef.current?.export('JPEG', 'diagram.jpg');
};Characteristics:
- Lossy compression
- Smallest file size
- Best for photographs
- No transparency
PDF Export
Portable Document Format - ideal for printing and sharing.
const exportAsPDF = () => {
chartRef.current?.export('PDF', 'diagram.pdf');
};Characteristics:
- Scalable without quality loss
- Professional appearance
- Print-optimized
- Can include text and metadata
SVG Export
Scalable Vector Graphics - infinite zoom without quality loss.
const exportAsSVG = () => {
chartRef.current?.export('SVG', 'diagram.svg');
};Characteristics:
- Vector format (scalable)
- Editable with design tools
- Smallest file for simple diagrams
- Support for animations
Export Configuration
Custom Export Filename
const exportWithCustomName = () => {
const timestamp = new Date().toISOString().split('T')[0];
chartRef.current?.export('PNG', `energy-flow-${timestamp}.png`);
};Export with Orientation
const exportPDF = () => {
// For landscape orientation
chartRef.current?.export('PDF', 'diagram.pdf');
};Multiple Format Export
import React, { useRef } from 'react';
function MultiFormatExport() {
const chartRef = useRef(null);
const exportFormats = [
{ format: 'PNG', label: 'PNG Image' },
{ format: 'PDF', label: 'PDF Document' },
{ format: 'SVG', label: 'Vector (SVG)' }
];
const handleExport = (format) => {
const filename = `sankey-export-${Date.now()}`;
chartRef.current?.export(format, filename);
};
return (
<div>
<fieldset>
<legend>Export Format</legend>
{exportFormats.map(({ format, label }) => (
<div key={format}>
<button onClick={() => handleExport(format)}>
{label}
</button>
</div>
))}
</fieldset>
<SankeyComponent
ref={chartRef}
width="90%"
height="420px"
title="Exportable Diagram"
>
{/* nodes and links */}
<Inject services={[SankeyExport]} />
</SankeyComponent>
</div>
);
}
export default MultiFormatExport;Print Functionality
Browser Print
Use standard browser print dialog:
const printChart = () => {
window.print();
};Print Configuration
import React, { useRef } from 'react';
function PrintableSankey() {
const chartRef = useRef(null);
const printWindow = useRef(null);
const handlePrint = () => {
printWindow.current = window.open('', '', 'height=500,width=800');
printWindow.current?.document.write(
'<html><head><title>Print Sankey</title></head><body>'
);
// Get chart SVG or canvas
const svgElement = chartRef.current?.svgObject;
if (svgElement) {
printWindow.current?.document.write(svgElement.outerHTML);
}
printWindow.current?.document.write('</body></html>');
printWindow.current?.document.close();
printWindow.current?.print();
};
return (
<div>
<button onClick={handlePrint}>Print Chart</button>
<SankeyComponent
ref={chartRef}
width="90%"
height="420px"
title="Energy Flow Analysis"
>
{/* nodes and links */}
</SankeyComponent>
</div>
);
}
export default PrintableSankey;Complete Export Example
import React from 'react';
import React, { useRef } from 'react';
import { SankeyComponent } from '@syncfusion/ej2-react-charts';
import {
SankeyComponent, Inject, SankeyTooltip, SankeyLegend,
SankeyNodeDirective, SankeyExport,
SankeyNodesCollectionDirective,
SankeyLinkDirective,
SankeyLinksCollectionDirective
} from '@syncfusion/ej2-react-charts';
import * as ReactDOM from "react-dom";
function ExportableSankey() {
const chartRef = useRef(null);
const exportChart = (format) => {
if (chartRef.current) {
const fileName = `sankey-diagram-${new Date().getTime()}.${format.toLowerCase()}`;
chartRef.current.export(format, fileName);
}
};
return (
<div>
<div style={{ marginBottom: '15px' }}>
<button onClick={() => exportChart('PNG')}>Export as PNG</button>
<button onClick={() => exportChart('PDF')}>Export as PDF</button>
<button onClick={() => exportChart('SVG')}>Export as SVG</button>
<button onClick={() => window.print()}>Print</button>
</div>
<SankeyComponent
ref={chartRef}
width="90%"
height="420px"
title="Energy Flow"
>
<SankeyNodesCollectionDirective>
<SankeyNodeDirective id="Solar" label={{ text: 'Solar' }} />
<SankeyNodeDirective id="Wind" label={{ text: 'Wind' }} />
<SankeyNodeDirective id="Natural Gas" label={{ text: 'Natural Gas' }} />
<SankeyNodeDirective id="Generation" label={{ text: 'Generation' }} />
<SankeyNodeDirective id="Residential" label={{ text: 'Residential' }} />
<SankeyNodeDirective id="Commercial" label={{ text: 'Commercial' }} />
<SankeyNodeDirective id="Industrial" label={{ text: 'Industrial' }} />
</SankeyNodesCollectionDirective>
<SankeyLinksCollectionDirective>
<SankeyLinkDirective sourceId="Solar" targetId="Generation" value={450} />
<SankeyLinkDirective sourceId="Wind" targetId="Generation" value={200} />
<SankeyLinkDirective sourceId="Natural Gas" targetId="Generation" value={800} />
<SankeyLinkDirective sourceId="Generation" targetId="Residential" value={300} />
<SankeyLinkDirective sourceId="Generation" targetId="Commercial" value={400} />
<SankeyLinkDirective sourceId="Generation" targetId="Industrial" value={350} />
</SankeyLinksCollectionDirective>
<Inject services={[SankeyTooltip, SankeyLegend, SankeyExport]} />
</SankeyComponent>
</div>
);
}
export default ExportableSankey;
ReactDOM.render(<ExportableSankey />, document.getElementById("charts"));Best Practices
1. Choose appropriate format - PNG for web, PDF for printing, SVG for editing 2. Provide filename context - Include date or data type in filename 3. Test exports - Verify quality in different applications 4. Include metadata - Add title, date, and source information 5. Optimize file size - Use compression for large exports 6. User-friendly options - Clear labels and button placement 7. Batch export - Allow exporting multiple formats at once 8. Error handling - Handle export failures gracefully
Getting Started with Sankey Chart
Table of Contents
- Installation and Setup
- Prerequisites
- Installing Syncfusion Sankey Package
- Package Dependencies
- Setting Up Your React Environment
- Using Vite (Recommended)
- Using Create React App
- Basic Sankey Component Setup
- Minimal Example
- Module Injection
- Available Modules
- Injecting Modules
- Real-World Example with Data
- Running Your Application
- Next Steps
Installation and Setup
Prerequisites
- Node.js version 14 or later
- React 16.8 or higher
- Basic knowledge of React and TypeScript (recommended)
- A code editor like Visual Studio Code
Installing Syncfusion Sankey Package
All Essential JS 2 packages are published in the npmjs.com public registry.
Install the React Charts package containing the Sankey component:
npm install @syncfusion/ej2-react-charts --saveThe --save flag includes the package in your package.json dependencies.
Package Dependencies
The Sankey Chart relies on several Syncfusion packages:
@syncfusion/ej2-react-charts
├── @syncfusion/ej2-base
├── @syncfusion/ej2-data
├── @syncfusion/ej2-charts
├── @syncfusion/ej2-react-base
├── @syncfusion/ej2-pdf-export
├── @syncfusion/ej2-file-utils
├── @syncfusion/ej2-compression
└── @syncfusion/ej2-svg-baseAll dependencies are automatically installed with the main package.
Setting Up Your React Environment
Using Vite (Recommended)
Vite provides fast development with instant HMR (Hot Module Replacement):
npm create vite@latest my-sankey-appWhen prompted, select React and your preferred variant (JavaScript or TypeScript).
For TypeScript:
npm create vite@latest my-sankey-app -- --template react-ts
cd my-sankey-app
npm run devFor JavaScript:
npm create vite@latest my-sankey-app -- --template react
cd my-sankey-app
npm run devUsing Create React App
Alternatively, use create-react-app (slower build but widely familiar):
npx create-react-app my-sankey-app
cd my-sankey-app
npm startBasic Sankey Component Setup
Minimal Example
Create a basic Sankey chart in your App.tsx or App.jsx:
import React from 'react';
import {
SankeyComponent,
SankeyNodeDirective,
SankeyNodesCollectionDirective,
SankeyLinkDirective,
SankeyLinksCollectionDirective,
Inject
} from '@syncfusion/ej2-react-charts';
import * as ReactDOM from "react-dom";
function App() {
return (
<div style={{ padding: '20px' }}>
<SankeyComponent
width="90%"
height="420px"
title="Simple Sankey Chart"
>
<SankeyNodesCollectionDirective>
<SankeyNodeDirective id="A" label={{ text: 'Node A' }} />
<SankeyNodeDirective id="B" label={{ text: 'Node B' }} />
<SankeyNodeDirective id="C" label={{ text: 'Node C' }} />
</SankeyNodesCollectionDirective>
<SankeyLinksCollectionDirective>
<SankeyLinkDirective sourceId="A" targetId="B" value={100} />
<SankeyLinkDirective sourceId="B" targetId="C" value={80} />
</SankeyLinksCollectionDirective>
</SankeyComponent>
</div>
);
}
export default App;
ReactDOM.render(<App />, document.getElementById("charts"));Understanding the Structure
- SankeyComponent - The main container for the diagram
- SankeyNodeDirective - Defines individual nodes (categories)
- SankeyLinkDirective - Defines connections between nodes with flow values
- width/height - Dimensions for the chart (supports %, px)
- title - Display text shown above the diagram
Module Injection
The Sankey Chart requires explicit module injection to enable features like tooltips, legends, and export functionality.
Available Modules
import {
SankeyTooltip, // Enable tooltip on hover
SankeyLegend, // Show legend
SankeyExport // Enable export functionality
} from '@syncfusion/ej2-react-charts';Injecting Modules
Add modules to your component using the <Inject> component:
<SankeyComponent
width="90%"
height="420px"
title="Chart with Features"
tooltip={{ enable: true }}
legendSettings={{ visible: true }}
>
<SankeyNodesCollectionDirective>
{/* nodes */}
</SankeyNodesCollectionDirective>
<SankeyLinksCollectionDirective>
{/* links */}
</SankeyLinksCollectionDirective>
<Inject services={[SankeyTooltip, SankeyLegend, SankeyExport]} />
</SankeyComponent>Real-World Example with Data
Here's a practical energy flow diagram:
import React from 'react';
import {
SankeyComponent, Inject, SankeyTooltip, SankeyLegend,
SankeyNodeDirective,
SankeyNodesCollectionDirective,
SankeyLinkDirective,
SankeyLinksCollectionDirective
} from '@syncfusion/ej2-react-charts';
import * as ReactDOM from "react-dom";
function EnergyFlowDashboard() {
return (
<div className="control-pane">
<div className="control-section">
<SankeyComponent
width="90%"
height="450px"
title="2024 Energy Consumption"
subTitle="By Source and Sector"
tooltip={{ enable: true }}
legendSettings={{ visible: true, position: 'Bottom' }}
>
<SankeyNodesCollectionDirective>
<SankeyNodeDirective id="Solar" label={{ text: 'Solar' }} />
<SankeyNodeDirective id="Wind" label={{ text: 'Wind' }} />
<SankeyNodeDirective id="Natural Gas" label={{ text: 'Natural Gas' }} />
<SankeyNodeDirective id="Generation" label={{ text: 'Generation' }} />
<SankeyNodeDirective id="Residential" label={{ text: 'Residential' }} />
<SankeyNodeDirective id="Commercial" label={{ text: 'Commercial' }} />
<SankeyNodeDirective id="Industrial" label={{ text: 'Industrial' }} />
</SankeyNodesCollectionDirective>
<SankeyLinksCollectionDirective>
<SankeyLinkDirective sourceId="Solar" targetId="Generation" value={450} />
<SankeyLinkDirective sourceId="Wind" targetId="Generation" value={200} />
<SankeyLinkDirective sourceId="Natural Gas" targetId="Generation" value={800} />
<SankeyLinkDirective sourceId="Generation" targetId="Residential" value={300} />
<SankeyLinkDirective sourceId="Generation" targetId="Commercial" value={400} />
<SankeyLinkDirective sourceId="Generation" targetId="Industrial" value={350} />
</SankeyLinksCollectionDirective>
<Inject services={[SankeyTooltip, SankeyLegend]} />
</SankeyComponent>
</div>
</div>
);
}
export default EnergyFlowDashboard;
ReactDOM.render(<EnergyFlowDashboard />, document.getElementById("charts"));Running Your Application
Start the development server:
npm run devYour Sankey Chart will be available at http://localhost:5173 (Vite) or http://localhost:3000 (Create React App).
Next Steps
- Configure Nodes & Links - Learn about node positioning and link styling in Nodes and Links Configuration
- Add Labels - Customize text and positioning in Labels and Positioning
- Enable Interactivity - Add tooltips and events in Interactivity and Events
Interactivity and Events
Table of contents
- Tooltip Configuration
- Basic Tooltip Setup
- Tooltip Properties
- Customized Tooltip
- Default Tooltip Content
- Template-Based Tooltips
- Event Handling
- Available Events
- Basic Event Handler
- Link Click Event
- Load Event
- User Interactions - Highlighting
- Hover Highlighting
- Best Practices
Tooltip Configuration
Tooltips display detailed information when users hover over nodes or links.
Basic Tooltip Setup
<SankeyComponent
width="90%"
height="420px"
title="Chart with Tooltips"
tooltip={{ enable: true }}
>
{/* nodes and links */}
<Inject services={[SankeyTooltip]} />
</SankeyComponent>Tooltip Properties
| Property | Type | Purpose |
|---|---|---|
enable | boolean | Enable/disable tooltip display |
fill | string | Tooltip background color |
textStyle | object | Font styling (size, family, color) |
border | object | Border configuration |
opacity | number | Background opacity (0-1) |
Customized Tooltip
<SankeyComponent
title="Custom Tooltips"
tooltip={{
enable: true,
fill: '#2E3440', // Dark background
textStyle: {
color: '#ECEFF4', // Light text
size: 12,
fontFamily: 'Arial'
}
}}
>
{/* nodes and links */}
<Inject services={[SankeyTooltip]} />
</SankeyComponent>Default Tooltip Content
By default, tooltips show:
- For Nodes: Node ID and label
- For Links: Source, Target, and Flow Value
Node: Solar
Label: Solar Energy
Source: Solar → Target: Generation
Value: 450 unitsTemplate-Based Tooltips
Customize tooltip content using templates (advanced):
import React from 'react';
function CustomTooltipSankey() {
return (
<SankeyComponent
title="Templated Tooltips"
tooltip={{
enable: true,
nodeTemplate: '${name}: ${value}KX',
linkTemplate: '${start.name}: ${start.out} KW → ${target.name}: ${target.in} KW'
}}
>
{/* nodes and links */}
<Inject services={[SankeyTooltip]} />
</SankeyComponent>
);
}
export default CustomTooltipSankey;Note: Tooltip contents can be formatted using nodeFormat and linkFormat for nodes and links respectively.
Event Handling
Available Events
| Event | Trigger | Use Case |
|---|---|---|
nodeClick | Node is clicked | Track selections, drill-down |
linkClick | Link is clicked | Analyze flow, filter data |
load | Chart fully loaded | Initialize, fetch data |
loaded | Chart rendering complete | Post-render operations |
tooltipRender | Tooltip about to show | Custom tooltip content |
Basic Event Handler
import React, { useState } from 'react';
function SankeyWithClickEvents() {
const [selectedNode, setSelectedNode] = useState(null);
const onNodeClick = (args) => {
console.log('Node clicked:', args.data);
setSelectedNode(args.data.id);
};
return (
<div>
{selectedNode && (
<p>Selected Node: {selectedNode}</p>
)}
<SankeyComponent
width="90%"
height="420px"
title="Interactive Nodes"
nodeClick={onNodeClick}
>
{/* nodes and links */}
</SankeyComponent>
</div>
);
}
export default SankeyWithClickEvents;Link Click Event
function SankeyWithLinkEvents() {
const onLinkClick = (args) => {
const { source, target, value } = args.data;
console.log(`Flow: ${source} → ${target} = ${value}`);
// Perform analytics or filtering
analyzeFlow(source, target, value);
};
return (
<SankeyComponent
title="Track Link Flows"
linkClick={onLinkClick}
>
{/* nodes and links */}
</SankeyComponent>
);
}Load Event
function SankeyWithLoadEvent() {
const onChartLoad = (args) => {
console.log('Chart loaded, initializing features...');
// Initialize tooltips, legends, etc.
};
const onChartLoaded = (args) => {
console.log('Chart rendering complete');
// Update UI, store reference
};
return (
<SankeyComponent
title="With Load Events"
load={onChartLoad}
loaded={onChartLoaded}
>
{/* nodes and links */}
</SankeyComponent>
);
}User Interactions - Highlighting
Hover Highlighting
Highlighting for Sankey nodes and links is enabled by default. The highlight opacity for both nodes and links can be customized using the highlightOpacity and inactiveOpacity properties.
import React, { useState } from 'react';
function SankeyWithHoverHighlight() {
return (
<SankeyComponent
title="Hover to Highlight"
>
<SankeyNodesCollectionDirective>
<SankeyNodeDirective
id="A"
label={{ text: 'Node A' }}
/>
{/* More nodes */}
</SankeyNodesCollectionDirective>
<Inject services={[SankeyTooltip]} />
</SankeyComponent>
);
}
export default SankeyWithHoverHighlight;Best Practices
1. Provide visual feedback - Highlight selected items 2. Keep tooltips concise - Show relevant info without clutter 3. Use consistent events - Standard click patterns across app 4. Handle edge cases - Empty selections, multiple clicks 5. Performance - Avoid heavy operations in event handlers 6. Mobile considerations - Touch events instead of hover 7. Accessibility - Keyboard alternatives to mouse events
Labels and Positioning
Table of contents
- Label Configuration
- Label Settings Properties
- Global vs. Per-Node Labels
- Node Labels
- Basic Node Label
- Styled Node Label
- Label Visibility Control
- Title and Subtitle
- Basic Title and Subtitle
- Styled Title Example
- Dynamic Titles
- Label Formatting
- Number Formatting in Labels
- Conditional Label Formatting
- Handling Label Overflow
- Strategy 1: Abbreviate Labels
- Strategy 2: Increase Chart Height
- Strategy 3: Conditional Label Visibility
- Strategy 4: Use Tooltips Instead
- Complete Overflow Handling Example
- Best Practices
Label Configuration
Labels provide text context for nodes and the overall diagram. Control visibility and positioning through labelSettings.
Label Settings Properties
<SankeyComponent
labelSettings={{
visible: true, // Label text transparency
fontSize: 12, // Font size in pixels
fontFamily: 'Arial', // Font family
fontWeight: 'normal' // Font weight
}}
>
{/* nodes and links */}
</SankeyComponent>Global vs. Per-Node Labels
Global Configuration:
<SankeyComponent
labelSettings={{
visible: true,
fontSize: 14,
fontFamily: 'Segoe UI'
}}
>
{/* All nodes use these settings */}
</SankeyComponent>Per-Node Customization:
<SankeyNodeDirective
id="Node1"
label={{
text: 'Custom Label',
fill: '#333', // Text color
fontSize: 14,
textOpacity: 0.9
}}
/>Node Labels
Each node can display text that identifies it in the diagram.
Basic Node Label
<SankeyNodeDirective
id="Energy"
label={{ text: 'Energy Input' }}
/>Styled Node Label
<SankeyNodesCollectionDirective>
<SankeyNodeDirective
id="Source"
label={{
text: 'Data Source',
fill: '#FFFFFF', // Text color
textOpacity: 1,
fontSize: 13,
fontFamily: 'Courier New',
fontWeight: 'bold'
}}
/>
<SankeyNodeDirective
id="Destination"
label={{
text: 'Output',
fill: '#333333',
fontSize: 12
}}
/>
</SankeyNodesCollectionDirective>Label Visibility Control
Hide labels for specific nodes or based on conditions:
import React, { useState } from 'react';
import {
SankeyComponent, Inject, SankeyTooltip, SankeyLegend, SankeyExport,
SankeyNodeDirective,
SankeyNodesCollectionDirective,
SankeyLinkDirective,
SankeyLinksCollectionDirective
} from '@syncfusion/ej2-react-charts';
import * as ReactDOM from "react-dom";
function SankeyWithTogglableLabels() {
const [showLabels, setShowLabels] = useState(true);
return (
<div>
<button onClick={() => setShowLabels(!showLabels)}>
Toggle Labels
</button>
<SankeyComponent
width="90%"
height="420px"
title="Selective Labels"
labelSettings={{ visible: showLabels }}
>
<SankeyNodesCollectionDirective>
<SankeyNodeDirective id="A" label={{ text: 'Node A' }} />
<SankeyNodeDirective id="B" label={{ text: 'Node B' }} />
<SankeyNodeDirective id="C" label={{ text: 'Node C' }} />
</SankeyNodesCollectionDirective>
<SankeyLinksCollectionDirective>
<SankeyLinkDirective sourceId="A" targetId="B" value={100} />
<SankeyLinkDirective sourceId="B" targetId="C" value={80} />
</SankeyLinksCollectionDirective>
<Inject services={[SankeyTooltip, SankeyLegend]} />
</SankeyComponent>
</div>
);
}
export default SankeyWithTogglableLabels;
ReactDOM.render(<SankeyWithTogglableLabels />, document.getElementById("charts"));Title and Subtitle
Provide context with chart title and subtitle displayed above the diagram.
Basic Title and Subtitle
<SankeyComponent
width="90%"
height="420px"
title="Energy Flow 2024"
subTitle="California Consumption by Sector"
>
{/* nodes and links */}
</SankeyComponent>Styled Title Example
<SankeyComponent
width="90%"
height="500px"
title="Supply Chain Flow"
subTitle="Product movement from suppliers to customers"
titleStyle={{
fontFamily: 'Arial',
size: '18px',
color: '#2E3440'
}}
>
{/* nodes and links */}
</SankeyComponent>Dynamic Titles
Update titles based on data or user selection:
import React, { useState } from 'react';
function DynamicTitleSankey() {
const [selectedYear, setSelectedYear] = useState(2024);
const getTitle = (year) => {
return `Energy Consumption ${year}`;
};
const getSubtitle = (year) => {
return `Annual flow analysis for year ${year}`;
};
return (
<div>
<select onChange={(e) => setSelectedYear(parseInt(e.target.value))}>
<option value={2022}>2022</option>
<option value={2023}>2023</option>
<option value={2024}>2024</option>
</select>
<SankeyComponent
width="90%"
height="420px"
title={getTitle(selectedYear)}
subTitle={getSubtitle(selectedYear)}
key={selectedYear}
>
{/* nodes and links vary by year */}
</SankeyComponent>
</div>
);
}
export default DynamicTitleSankey;Label Formatting
Format labels to enhance readability and information density.
Number Formatting in Labels
function formatFlow(value) {
if (value >= 1000000) {
return (value / 1000000).toFixed(1) + 'M';
} else if (value >= 1000) {
return (value / 1000).toFixed(1) + 'K';
}
return value.toString();
}
// Use in labels
<SankeyNodeDirective
id="Input"
label={{
text: `Input: ${formatFlow(150000)}`
}}
/>Conditional Label Formatting
Show different information based on node type:
function getLabelText(nodeId, nodeType) {
switch(nodeType) {
case 'source':
return `Source: ${nodeId}`;
case 'processing':
return `Process: ${nodeId}`;
case 'destination':
return `Output: ${nodeId}`;
default:
return nodeId;
}
}
<SankeyNodeDirective
id="A"
label={{ text: getLabelText('A', 'source') }}
/>Handling Label Overflow
Labels can overflow when text is long or space is limited. Implement strategies to manage this.
Strategy 1: Abbreviate Labels
Shorten long node names:
function abbreviate(text, maxLength = 15) {
if (text.length > maxLength) {
return text.substring(0, maxLength - 3) + '...';
}
return text;
}
<SankeyNodeDirective
id="LongNodeName"
label={{ text: abbreviate('Very Long Process Name Here') }}
/>Strategy 2: Increase Chart Height
Give more vertical space to accommodate labels:
import { Browser } from '@syncfusion/ej2-base';
<SankeyComponent
width="90%"
height={Browser.isDevice ? '700px' : '500px'}
title="Sankey with More Space"
>
{/* nodes and links */}
</SankeyComponent>Strategy 3: Conditional Label Visibility
Hide labels on small devices:
import { Browser } from '@syncfusion/ej2-base';
<SankeyComponent
width="90%"
height={Browser.isDevice ? '600px' : '450px'}
labelSettings={{
visible: !Browser.isDevice // Only show on desktop
}}
>
{/* nodes and links */}
</SankeyComponent>Strategy 4: Use Tooltips Instead
Move detailed information to tooltips:
<SankeyComponent
title="Energy Flow"
labelSettings={{
visible: true,
fontSize: 10 // Smaller labels
}}
tooltip={{ enable: true }}
>
<SankeyNodesCollectionDirective>
<SankeyNodeDirective
id="Node1"
label={{ text: 'N1' }} // Abbreviated
/>
{/* Tooltip will show full name on hover */}
</SankeyNodesCollectionDirective>
<Inject services={[SankeyTooltip]} />
</SankeyComponent>Complete Overflow Handling Example
import React, { useState } from 'react';
import { Browser } from '@syncfusion/ej2-base';
import {
SankeyComponent, Inject, SankeyTooltip, SankeyLegend, SankeyExport,
SankeyNodeDirective,
SankeyNodesCollectionDirective,
SankeyLinkDirective,
SankeyLinksCollectionDirective
} from '@syncfusion/ej2-react-charts';
import * as ReactDOM from "react-dom";
function SmartLabelSankey() {
const [labelMode, setLabelMode] = useState('auto');
const nodes = [
{ id: 'Source1', fullName: 'Primary Data Source' },
{ id: 'Source2', fullName: 'Secondary Data Source' },
{ id: 'Process', fullName: 'Data Processing Pipeline' },
{ id: 'Output', fullName: 'Final Output' }
];
const getDisplayLabel = (node) => {
if (labelMode === 'full') return node.fullName;
if (labelMode === 'abbreviated') {
return node.fullName.substring(0, 10) + '...';
}
return node.id;
};
return (
<div>
<div>
<label>Label Mode: </label>
<select onChange={(e) => setLabelMode(e.target.value)}>
<option value="auto">Auto</option>
<option value="abbreviated">Abbreviated</option>
<option value="full">Full</option>
</select>
</div>
<SankeyComponent
width="90%"
height={Browser.isDevice ? '700px' : '500px'}
labelSettings={{
visible: labelMode !== 'hidden',
fontSize: labelMode === 'full' ? 10 : 12
}}
>
<SankeyNodesCollectionDirective>
{nodes.map(node => (
<SankeyNodeDirective
key={node.id}
id={node.id}
label={{ text: getDisplayLabel(node) }}
/>
))}
</SankeyNodesCollectionDirective>
<SankeyLinksCollectionDirective>
<SankeyLinkDirective sourceId="Source1" targetId="Process" value={100} />
<SankeyLinkDirective sourceId="Source2" targetId="Process" value={75} />
<SankeyLinkDirective sourceId="Process" targetId="Output" value={150} />
</SankeyLinksCollectionDirective>
<Inject services={[SankeyTooltip, SankeyLegend]} />
</SankeyComponent>
</div>
);
}
export default SmartLabelSankey;
ReactDOM.render(<SmartLabelSankey />, document.getElementById("charts"));Best Practices
1. Keep labels concise - Aim for 1-3 words per label 2. Use consistent formatting - Apply styles uniformly 3. Leverage tooltips - Show full details on hover 4. Test on mobile - Ensure labels work on small screens 5. Contrast matters - Use readable label colors against backgrounds 6. Group related labels - Similar node types should have similar styling
Legend and Display Options
Table of Contents
- Legend Configuration
- Basic Legend Setup
- Legend Properties
- Legend Positioning
- Bottom Position (Default)
- Top Position
- Right Position
- Left Position
- Display Options and Styling
- Show/Hide Legend Conditionally
- Legend with Border and Background
- Styled Legend Text
- Theming and Color Customization
- Node Color Assignment
- Color Schemes for Categories
- Link Color Inheritance
- Responsive Display
- Mobile-Responsive Legend
- Adaptive Display Configuration
- Display Modes
- Compact Display
- Full Information Display
- Interactive Display
- Best Practices
Legend Configuration
The legend displays visual indicators for nodes in your Sankey diagram, helping users understand the flow representation.
Basic Legend Setup
<SankeyComponent
width="90%"
height="420px"
title="Chart with Legend"
legendSettings={{
visible: true, // Show legend
position: 'Bottom' // Legend position
}}
>
{/* nodes and links */}
<Inject services={[SankeyLegend]} />
</SankeyComponent>Legend Properties
| Property | Type | Options |
|---|---|---|
visible | boolean | true \ |
position | string | 'Top' \ |
itemPadding | number | Spacing between legend items (pixels) |
border | object | Border configuration |
background | string | Legend background color |
textStyle | object | Text styling options |
Legend Positioning
Position the legend based on your diagram layout and content flow.
Bottom Position (Default)
<SankeyComponent
title="Energy Flow"
legendSettings={{
visible: true,
position: 'Bottom',
itemPadding: 8
}}
>
{/* nodes and links */}
</SankeyComponent>Best For: Horizontal space availability, wide diagrams
Top Position
<SankeyComponent
title="Process Flow"
legendSettings={{
visible: true,
position: 'Top',
itemPadding: 8
}}
>
{/* nodes and links */}
</SankeyComponent>Best For: Mobile layouts, content below chart
Right Position
<SankeyComponent
width="70%"
height="500px"
title="Vertical Flow"
legendSettings={{
visible: true,
position: 'Right',
itemPadding: 10
}}
>
{/* nodes and links */}
</SankeyComponent>Best For: Tall diagrams with horizontal space
Left Position
<SankeyComponent
width="70%"
height="500px"
title="RTL Support"
legendSettings={{
visible: true,
position: 'Left',
itemPadding: 10
}}
>
{/* nodes and links */}
</SankeyComponent>Best For: Right-to-left layouts, RTL support
Display Options and Styling
Show/Hide Legend Conditionally
import React, { useState } from 'react';
function SankeyWithLegendToggle() {
const [showLegend, setShowLegend] = useState(true);
return (
<div>
<button onClick={() => setShowLegend(!showLegend)}>
{showLegend ? 'Hide' : 'Show'} Legend
</button>
<SankeyComponent
width="90%"
height="420px"
title="Toggleable Legend"
legendSettings={{
visible: showLegend,
position: 'Bottom'
}}
>
{/* nodes and links */}
</SankeyComponent>
</div>
);
}
export default SankeyWithLegendToggle;Legend with Border and Background
<SankeyComponent
legendSettings={{
visible: true,
position: 'Bottom',
itemPadding: 8,
border: {
color: '#CCCCCC',
width: 1
},
background: '#F5F5F5'
}}
>
{/* nodes and links */}
</SankeyComponent>Styled Legend Text
<SankeyComponent
legendSettings={{
visible: true,
position: 'Bottom',
textStyle: {
fontFamily: 'Arial',
size: 12,
bold: true,
color: '#333333'
}
}}
>
{/* nodes and links */}
</SankeyComponent>Theming and Color Customization
Node Color Assignment
Assign colors to nodes for visual distinction:
<SankeyNodesCollectionDirective>
<SankeyNodeDirective
id="Solar"
color="#FFD700" // Gold
label={{ text: 'Solar' }}
/>
<SankeyNodeDirective
id="Wind"
color="#87CEEB" // Sky blue
label={{ text: 'Wind' }}
/>
<SankeyNodeDirective
id="Natural Gas"
color="#FF6347" // Tomato
label={{ text: 'Natural Gas' }}
/>
<SankeyNodeDirective
id="Grid"
color="#32CD32" // Lime green
label={{ text: 'Grid' }}
/>
</SankeyNodesCollectionDirective>Color Schemes for Categories
Use consistent color schemes for different data categories:
const energySources = {
renewable: ['#FFD700', '#87CEEB', '#32CD32'], // Gold, Sky blue, Lime
fossil: ['#FF6347', '#8B4513', '#696969'], // Red, Brown, Gray
output: ['#FF69B4', '#00CED1', '#9370DB'] // Pink, Turquoise, Purple
};
<SankeyNodesCollectionDirective>
<SankeyNodeDirective id="Solar" color={energySources.renewable[0]} />
<SankeyNodeDirective id="Wind" color={energySources.renewable[1]} />
<SankeyNodeDirective id="Coal" color={energySources.fossil[0]} />
<SankeyNodeDirective id="Grid" color={energySources.output[0]} />
</SankeyNodesCollectionDirective>Link Color Inheritance
Configure how links inherit colors:
<SankeyComponent
linkStyle={{
colorType: 'Source', // Links use source node color
opacity: 0.6,
curvature: 0.55
}}
>
{/* nodes and links */}
</SankeyComponent>Responsive Display
Adapt legend and display options for different screen sizes.
Mobile-Responsive Legend
import { Browser } from '@syncfusion/ej2-base';
<SankeyComponent
width="100%"
height={Browser.isDevice ? '500px' : '420px'}
legendSettings={{
visible: true,
position: Browser.isDevice ? 'Bottom' : 'Right',
itemPadding: Browser.isDevice ? 4 : 8
}}
>
{/* nodes and links */}
</SankeyComponent>Adaptive Display Configuration
import React from 'react';
import { Browser } from '@syncfusion/ej2-base';
function ResponsiveSankey() {
const getDisplayConfig = () => {
if (Browser.isDevice) {
return {
width: '100%',
height: '600px',
legendPosition: 'Bottom',
legendVisible: true,
labelVisible: false,
tooltipEnabled: true
};
} else {
return {
width: '90%',
height: '500px',
legendPosition: 'Right',
legendVisible: true,
labelVisible: true,
tooltipEnabled: true
};
}
};
const config = getDisplayConfig();
return (
<SankeyComponent
width={config.width}
height={config.height}
labelSettings={{ visible: config.labelVisible }}
legendSettings={{
visible: config.legendVisible,
position: config.legendPosition
}}
tooltip={{ enable: config.tooltipEnabled }}
>
{/* nodes and links */}
<Inject services={[SankeyTooltip, SankeyLegend]} />
</SankeyComponent>
);
}
export default ResponsiveSankey;Display Modes
Compact Display
Minimize visual elements for space constraints:
<SankeyComponent
width="100%"
height="400px"
title="Compact View"
labelSettings={{
visible: false // Hide labels to save space
}}
legendSettings={{
visible: false // Hide legend
}}
tooltip={{ enable: false }}
>
{/* nodes and links */}
</SankeyComponent>Full Information Display
Show all details for presentation or analysis:
<SankeyComponent
width="100%"
height="600px"
title="Detailed Energy Flow 2024"
subTitle="Complete analysis by source and consumption sector"
labelSettings={{
visible: true,
fontSize: 13
}}
legendSettings={{
visible: true,
position: 'Bottom',
itemPadding: 10,
border: { color: '#CCCCCC', width: 1 },
background: '#F9F9F9'
}}
tooltip={{ enable: true }}
>
{/* nodes and links */}
<Inject services={[SankeyTooltip, SankeyLegend]} />
</SankeyComponent>Interactive Display
Allow users to control display options:
import React, { useState } from 'react';
import * as ReactDOM from 'react-dom';
import {
SankeyComponent,
Inject,
SankeyTooltip,
SankeyLegend,
SankeyExport,
SankeyNodeDirective,
SankeyNodesCollectionDirective,
SankeyLinkDirective,
SankeyLinksCollectionDirective,
} from '@syncfusion/ej2-react-charts';
function InteractiveSankey() {
const [displayOptions, setDisplayOptions] = useState({
showLegend: true,
showLabels: true,
showTooltips: true,
legendPosition: 'Bottom',
});
const handleToggle = (option) => {
setDisplayOptions((prev) => ({
...prev,
[option]: !prev[option],
}));
};
const handlePositionChange = (position) => {
setDisplayOptions((prev) => ({
...prev,
legendPosition: position,
}));
};
return (
<div>
<div style={{ marginBottom: '20px' }}>
<label>
<input
type="checkbox"
checked={displayOptions.showLegend}
onChange={() => handleToggle('showLegend')}
/>
Show Legend
</label>
<label style={{ marginLeft: '15px' }}>
<input
type="checkbox"
checked={displayOptions.showLabels}
onChange={() => handleToggle('showLabels')}
/>
Show Labels
</label>
<label style={{ marginLeft: '15px' }}>
Legend Position:
<select
value={displayOptions.legendPosition}
onChange={(e) => handlePositionChange(e.target.value)}
>
<option value="Top">Top</option>
<option value="Bottom">Bottom</option>
<option value="Left">Left</option>
<option value="Right">Right</option>
</select>
</label>
</div>
<SankeyComponent
width="90%"
height="420px"
title="Interactive Display"
labelSettings={{ visible: displayOptions.showLabels }}
legendSettings={{
visible: displayOptions.showLegend,
position: displayOptions.legendPosition,
}}
>
<SankeyNodesCollectionDirective>
<SankeyNodeDirective id="Solar" label={{ text: 'Solar' }} />
<SankeyNodeDirective id="Generation" label={{ text: 'Generation' }} />
<SankeyNodeDirective
id="Consumption"
label={{ text: 'Consumption' }}
/>
</SankeyNodesCollectionDirective>
<SankeyLinksCollectionDirective>
<SankeyLinkDirective
sourceId="Solar"
targetId="Generation"
value={450}
/>
<SankeyLinkDirective
sourceId="Generation"
targetId="Consumption"
value={400}
/>
</SankeyLinksCollectionDirective>
<Inject services={[SankeyTooltip, SankeyLegend]} />
</SankeyComponent>
</div>
);
}
export default InteractiveSankey;
ReactDOM.render(<InteractiveSankey />, document.getElementById('charts'));Best Practices
1. Choose appropriate position - Consider available space and content flow 2. Limit legend items - Too many items reduce readability 3. Consistent colors - Use color schemes across related data 4. Responsive positioning - Adapt legend position for mobile 5. Test visibility - Ensure legend is readable on all devices 6. Match theme - Align legend styling with overall application theme 7. Use meaningful labels - Legend items should be self-explanatory
Nodes and Links Configuration
Table of contents
- Node Structure
- Node Properties
- Essential Properties
- Basic Node Example
- Node Label Configuration
- Link Structure
- Link Properties
- Essential Properties
- Basic Link Example
- Data Binding Patterns
- Pattern 1: Static Nodes and Links
- Pattern 2: Dynamic Nodes and Links from State
- Pattern 3: Data from API
- Node Positioning
- Offset for Alignment
- Practical Example: Multi-Level Flow
- Link Styling
- Link Style Properties
- Color Type Options
- Link Styling Example
- Performance Optimization
- Large Dataset Handling
- Tips for Better Performance
Node Structure
Nodes represent categories or stages in your flow diagram. Each node is a destination/source point for links.
Node Properties
<SankeyNodeDirective
id="nodeIdentifier" // Unique identifier (required)
label={{ text: 'Display Label' }} // Label configuration
offset={0} // Position offset
color="blue" // Node fill color (optional)
/>Essential Properties
| Property | Type | Purpose |
|---|---|---|
id | string | Unique identifier for referencing in links |
label | object | Label configuration with text and styling |
offset | number | Vertical positioning offset in pixels |
color | string | Node fill color (hex or named color) |
Basic Node Example
<SankeyNodesCollectionDirective>
<SankeyNodeDirective
id="Source1"
label={{ text: 'Data Source' }}
/>
<SankeyNodeDirective
id="Processing"
label={{ text: 'Process Layer' }}
/>
<SankeyNodeDirective
id="Output"
label={{ text: 'Output' }}
/>
</SankeyNodesCollectionDirective>Node Label Configuration
Customize node labels with detailed properties:
<SankeyNodeDirective
id="Node1"
label={{
text: 'Custom Label',
fill: '#FFF', // Label text color
textOpacity: 1,
fontSize: 12,
fontFamily: 'Arial'
}}
/>Link Structure
Links represent the flow between nodes with specific values representing the magnitude of flow.
Link Properties
<SankeyLinkDirective
sourceId="source" // Source node ID (required)
targetId="target" // Target node ID (required)
value={100} // Flow magnitude (required)
/>Essential Properties
| Property | Type | Purpose |
|---|---|---|
sourceId | string | ID of the originating node |
targetId | string | ID of the destination node |
value | number | Flow quantity or weight |
Basic Link Example
<SankeyLinksCollectionDirective>
<SankeyLinkDirective sourceId="A" targetId="B" value={100} />
<SankeyLinkDirective sourceId="A" targetId="C" value={50} />
<SankeyLinkDirective sourceId="B" targetId="D" value={80} />
</SankeyLinksCollectionDirective>Data Binding Patterns
Pattern 1: Static Nodes and Links
Define all nodes and links declaratively:
<SankeyComponent title="Energy Flow">
<SankeyNodesCollectionDirective>
<SankeyNodeDirective id="Solar" label={{ text: 'Solar' }} />
<SankeyNodeDirective id="Wind" label={{ text: 'Wind' }} />
<SankeyNodeDirective id="Grid" label={{ text: 'Grid' }} />
</SankeyNodesCollectionDirective>
<SankeyLinksCollectionDirective>
<SankeyLinkDirective sourceId="Solar" targetId="Grid" value={450} />
<SankeyLinkDirective sourceId="Wind" targetId="Grid" value={200} />
</SankeyLinksCollectionDirective>
<Inject services={[SankeyTooltip, SankeyLegend]} />
</SankeyComponent>Pattern 2: Dynamic Nodes and Links from State
Use React state to manage node and link data:
import * as ReactDOM from "react-dom";
import React, { useState } from 'react';
import {
SankeyComponent, Inject, SankeyTooltip, SankeyLegend,
SankeyNodeDirective, SankeyNodesCollectionDirective,
SankeyLinkDirective, SankeyLinksCollectionDirective
} from '@syncfusion/ej2-react-charts';
function DynamicSankey() {
const [nodes] = useState([
{ id: 'A', label: { text: 'Source A' } },
{ id: 'B', label: { text: 'Source B' } },
{ id: 'Output', label: { text: 'Output' } }
]);
const [links] = useState([
{ sourceId: 'A', targetId: 'Output', value: 100 },
{ sourceId: 'B', targetId: 'Output', value: 75 }
]);
return (
<SankeyComponent width="90%" height="420px" title="Dynamic Data">
<SankeyNodesCollectionDirective>
{nodes.map((node) => (
<SankeyNodeDirective
key={node.id}
id={node.id}
label={node.label}
/>
))}
</SankeyNodesCollectionDirective>
<SankeyLinksCollectionDirective>
{links.map((link, index) => (
<SankeyLinkDirective
key={index}
sourceId={link.sourceId}
targetId={link.targetId}
value={link.value}
/>
))}
</SankeyLinksCollectionDirective>
<Inject services={[SankeyTooltip, SankeyLegend]} />
</SankeyComponent>
);
}
export default DynamicSankey;
ReactDOM.render(<DynamicSankey />, document.getElementById("charts"));Pattern 3: Data from API
Fetch and update flow data from a remote source:
import * as ReactDOM from "react-dom";
import React, { useState, useEffect } from 'react';
import {
SankeyComponent, Inject, SankeyTooltip, SankeyLegend,
SankeyNodeDirective, SankeyNodesCollectionDirective,
SankeyLinkDirective, SankeyLinksCollectionDirective
} from '@syncfusion/ej2-react-charts';
function APIBasedSankey() {
const [nodes, setNodes] = useState([]);
const [links, setLinks] = useState([]);
const [loading, setLoading] = useState(true);
useEffect(() => {
fetch('/api/sankey-data')
.then(res => res.json())
.then(data => {
setNodes(data.nodes);
setLinks(data.links);
setLoading(false);
})
.catch(err => {
console.error('Failed to load data:', err);
setLoading(false);
});
}, []);
if (loading) return <div>Loading...</div>;
return (
<SankeyComponent width="90%" height="420px" title="Live Data">
<SankeyNodesCollectionDirective>
{nodes.map((node) => (
<SankeyNodeDirective
key={node.id}
id={node.id}
label={node.label}
/>
))}
</SankeyNodesCollectionDirective>
<SankeyLinksCollectionDirective>
{links.map((link, index) => (
<SankeyLinkDirective
key={index}
sourceId={link.sourceId}
targetId={link.targetId}
value={link.value}
/>
))}
</SankeyLinksCollectionDirective>
<Inject services={[SankeyTooltip, SankeyLegend]} />
</SankeyComponent>
);
}
export default APIBasedSankey;
ReactDOM.render(<APIBasedSankey />, document.getElementById("charts"));Node Positioning
Control node vertical alignment using the offset property:
Offset for Alignment
<SankeyNodesCollectionDirective>
<SankeyNodeDirective
id="Top"
label={{ text: 'Top' }}
offset={-100} // Negative value: pull upward
/>
<SankeyNodeDirective
id="Middle"
label={{ text: 'Middle' }}
offset={0} // No offset: center
/>
<SankeyNodeDirective
id="Bottom"
label={{ text: 'Bottom' }}
offset={100} // Positive value: push downward
/>
</SankeyNodesCollectionDirective>Practical Example: Multi-Level Flow
Position nodes for a three-layer flow:
<SankeyComponent width="90%" height="600px">
<SankeyNodesCollectionDirective>
{/* Input Layer */}
<SankeyNodeDirective id="Input1" offset={-80} />
<SankeyNodeDirective id="Input2" offset={-40} />
{/* Processing Layer */}
<SankeyNodeDirective id="Process" offset={0} />
{/* Output Layer */}
<SankeyNodeDirective id="Output1" offset={-40} />
<SankeyNodeDirective id="Output2" offset={40} />
</SankeyNodesCollectionDirective>
<SankeyLinksCollectionDirective>
{/* Links between layers */}
</SankeyLinksCollectionDirective>
<Inject services={[SankeyTooltip, SankeyLegend]} />
</SankeyComponent>Link Styling
Link Style Properties
Control link appearance globally or per-link:
<SankeyComponent
linkStyle={{
opacity: 0.6, // Link transparency (0-1)
curvature: 0.55, // Link curve intensity (0-1)
colorType: 'Source' // 'Source' or other color strategy
}}
>
{/* nodes and links */}
</SankeyComponent>Color Type Options
| Option | Behavior |
|---|---|
'Source' | Links inherit color from source node |
'Target' | Links inherit color from target node |
| Custom hex | Static color for all links |
Link Styling Example
<SankeyComponent
title="Styled Links"
linkStyle={{
opacity: 0.5,
curvature: 0.7,
colorType: 'Source'
}}
>
<SankeyNodesCollectionDirective>
<SankeyNodeDirective id="A" color="#FF6B6B" />
<SankeyNodeDirective id="B" color="#4ECDC4" />
<SankeyNodeDirective id="C" />
</SankeyNodesCollectionDirective>
<SankeyLinksCollectionDirective>
<SankeyLinkDirective sourceId="A" targetId="C" value={100} />
<SankeyLinkDirective sourceId="B" targetId="C" value={75} />
</SankeyLinksCollectionDirective>
<Inject services={[SankeyTooltip, SankeyLegend]} />
</SankeyComponent>Performance Optimization
Large Dataset Handling
When dealing with hundreds of nodes or links:
1. Lazy Load Data - Load nodes/links in batches 2. Virtual Scrolling - For cases with many items 3. Simplify Rendering - Disable unnecessary features
function LargeDatasetSankey() {
const [displayNodes, setDisplayNodes] = useState([]);
const [displayLinks, setDisplayLinks] = useState([]);
useEffect(() => {
// Load first 100 nodes
const allNodes = generateAllNodes(1000);
setDisplayNodes(allNodes.slice(0, 100));
const allLinks = generateAllLinks(1000);
setDisplayLinks(allLinks.slice(0, 200));
}, []);
return (
<SankeyComponent
width="90%"
height="600px"
>
<SankeyNodesCollectionDirective>
{displayNodes.map(node => (
<SankeyNodeDirective key={node.id} {...node} />
))}
</SankeyNodesCollectionDirective>
<SankeyLinksCollectionDirective>
{displayLinks.map((link, i) => (
<SankeyLinkDirective key={i} {...link} />
))}
</SankeyLinksCollectionDirective>
</SankeyComponent>
);
}Tips for Better Performance
- Use React keys properly for list rendering
- Avoid inline object creation in render methods
- Consider memoization for expensive calculations
- Limit link count per node to maintain responsiveness
````markdown
Sankey Events Reference
Source: SankeyComponent API events
Below are events exposed by SankeyComponent. Complex event argument types link to their API pages.
afterExport(args)— (see component exports) — Fired after export completes.beforeExport(args)— SankeyExportEventArgs — Fired before export starts; cancelable.beforePrint(args)— SankeyPrintEventArgs — Fired before print starts.exportCompleted(args)— SankeyExportedEventArgs — Fired after export completes.labelRendering(args)— SankeyLabelRenderEventArgs — Fired before a label is rendered; allows customization.legendItemHover(args)— SankeyLegendItemHoverEventArgs — When mouse hovers a legend item.legendItemRendering(args)— SankeyLegendRenderEventArgs — Fired before a legend item renders; customize label/shape.linkClick(args)— SankeyLinkEventArgs — Fired when a link is clicked.linkEnter(args)— SankeyLinkEventArgs — Fired when mouse enters a link.linkLeave(args)— SankeyLinkEventArgs — Fired when mouse leaves a link.linkRendering(args)— SankeyLinkRenderEventArgs — Fired before a link is rendered; allows style overrides.load(args)— SankeyLoadedEventArgs — Fired before the sankey loads; use to modify initial config.loaded(args)— SankeyLoadedEventArgs — Fired after the sankey fully loads.nodeClick(args)— SankeyNodeEventArgs — Fired when a node is clicked.nodeEnter(args)— SankeyNodeEventArgs — Fired when mouse enters a node.nodeLeave(args)— SankeyNodeEventArgs — Fired when mouse leaves a node.nodeRendering(args)— SankeyNodeRenderEventArgs — Fired before a node renders; allows customization.sizeChanged(args)— SankeySizeChangedEventArgs — Fired when chart size changes.tooltipRendering(args)— SankeyTooltipRenderEventArgs — Fired before a tooltip is shown.
Usage
Attach handlers directly to the component:
<SankeyComponent
beforeExport={(args) => {/* ... */}}
linkClick={(args) => {/* ... */}}
tooltipRendering={(args) => {/* ... */}}
>
{/* ... */}
</SankeyComponent>Follow linked argument pages for full args object shapes and available fields.
````
````markdown
Sankey Examples Reference
This file collects example patterns referenced from SKILL.md:
basic-usage
<SankeyComponent width="90%" height="420px" title="Energy Flow" tooltip={{ enable: true }}>
<SankeyNodesCollectionDirective>
<SankeyNodeDirective id="Solar" label={{ text: 'Solar' }} />
<SankeyNodeDirective id="Generation" label={{ text: 'Generation' }} />
<SankeyNodeDirective id="Consumption" label={{ text: 'Consumption' }} />
</SankeyNodesCollectionDirective>
<SankeyLinksCollectionDirective>
<SankeyLinkDirective sourceId="Solar" targetId="Generation" value={450} />
<SankeyLinkDirective sourceId="Generation" targetId="Consumption" value={400} />
</SankeyLinksCollectionDirective>
<Inject services={[SankeyTooltip, SankeyLegend, SankeyExport]} />
</SankeyComponent>custom-node-styles
<SankeyComponent
linkStyle={{ opacity: 0.6, curvature: 0.55, colorType: 'Source' }}
nodeWidth={12}
nodePadding={10}
>
{/* nodes & links */}
</SankeyComponent>tooltip-template
<SankeyComponent
tooltip={{ enable: true, template: `<div>{source} → {target}: {value}</div>` }}
tooltipRender={(args) => { args.text = `${args.data.source} → ${args.data.target}: ${args.data.value}`; }}
>
{/* nodes & links */}
</SankeyComponent>export-and-print
const ref = useRef(null);
<button onClick={() => ref.current?.export('PNG', 'sankey')}>Export</button>
<SankeyComponent ref={ref} /* ... */ />````
````markdown
Sankey Methods Reference
See the component methods in the main API: SankeyComponent API - Methods
Common instance methods (summaries):
export(type: string, fileName?: string, orientation?: object)— Export the chart to supported formats ('png','jpeg','svg','pdf').print(id?: string)— Print the chart or a specific element by id.getModuleName()— Returns internal module name for the component.destroy()— Destroys the component instance and cleans up event listeners and DOM modifications.
Example
import React, { useRef } from 'react';
function ExportableSankey() {
const sankeyRef = useRef(null);
const handleExport = () => {
sankeyRef.current?.export('PNG', 'sankey-export');
};
const handlePrint = () => {
sankeyRef.current?.print();
};
return (
<div>
<button onClick={handleExport}>Export</button>
<button onClick={handlePrint}>Print</button>
<SankeyComponent ref={sankeyRef} width="90%" height="420px">
{/* nodes & links */}
</SankeyComponent>
</div>
);
}
export default ExportableSankey;````
````markdown
Sankey Props Reference
Source: SankeyComponent API
This file lists primary props for the SankeyComponent. Complex/nested props link to their model pages on the official Syncfusion docs.
Props
accessibility— AccessibilityModel — Accessibility options for the component.allowExport—boolean— default:false— Enables export in specific scenarios. See component API.animation— AnimationModel — Animation configuration for render transitions.background—string— default:null— Background color value.backgroundImage—string— default:null— URL for background image.border— BorderModel — Outer border configuration.enableExport—boolean— default:true— When true, enables export of the diagram into supported formats.enablePersistence—boolean— default:false— Persist component state between reloads.enableRtl—boolean— default:false— Enable right-to-left rendering.focusBorderColor—string— default:null— Focus border color for interactive elements.focusBorderMargin—number— default:0— Focus border margin.focusBorderWidth—number— default:1.5— Focus border width.height—string— default:null— Component height (e.g.,"420px"or"100%").labelSettings— SankeyLabelSettingsModel — Configure node and link labels.legendSettings— SankeyLegendSettingsModel — Legend configuration.linkStyle— SankeyLinkSettingsModel — Global link styling (opacity, colorType, curvature).links— [SankeyLinkModel[]](https://ej2.syncfusion.com/react/documentation/api/sankey/sankeylinkmodel) — default:[]— Collection of link definitions (source / target / value).locale—string— default:''— Culture/locale override for this component.margin— MarginModel — Margin configuration around the component.nodeLayoutMap—{ [key: string]: SankeyNodeLayout }— Computed node layout map (internal structure).nodeStyle— SankeyNodeSettingsModel — Node style configuration (size, color, text alignment).nodes— [SankeyNodeModel[]](https://ej2.syncfusion.com/react/documentation/api/sankey/sankeynodemodel) — default:[]— Collection of node definitions.orientation—Orientation— default:Horizontal— Diagram orientation (see API: orientation).subTitle—string— default:''— Subtitle text.subTitleStyle— SankeyTitleStyleModel — Subtitle style options.theme— ChartTheme — default:Material— Component theme.title—string— default:''— Main title text.titleStyle— SankeyTitleStyleModel — Title style options.tooltip— SankeyTooltipSettingsModel — Tooltip configuration (enable/template/format).width—string— default:null— Component width (e.g.,"90%"or"800px").
Notes
- This summary links to model pages for complex/nested props — follow those links for full property shapes and examples.
- Numeric defaults and enum token names (if you require absolute precision) should be verified against the official API live page: https://ej2.syncfusion.com/react/documentation/api/sankey/index-default
````