Material Icons
OrgChart JS is a powerful JavaScript library for visualizing hierarchical data structures. A common customization requirement is adding Material Icons to nodes. In this guide, we will walk through how to achieve this using the foreignObject element.
Step 1: Include Required Resources
To begin, include the necessary scripts and styles in the head section of your HTML file:
<script src="https://cdn.balkan.app/orgchart.js"></script>
<link href="https://fonts.googleapis.com/icon?family=Material+Icons" rel="stylesheet">This loads the OrgChart JS library and the Google Material Icons font.
Step 2: Create the Container
In your HTML body, add a div where the chart will be rendered:
<div id="tree"></div>Step 3: Define a Custom Template Field
OrgChart JS allows you to customize nodes using templates. Here, define a template field that includes a Material Icon inside a foreignObject:
OrgChart.templates.ana.icon =
`<foreignobject class="node" x="10" y="10" width="200" height="100">
<span class="material-icons">{val}</span>
</foreignobject>`;The {val} placeholder is dynamically replaced with the icon name. foreignObject allows regular HTML elements to be used inside SVG.
Step 4: Initialize the OrgChart
Next, initialize the OrgChart instance and configure the nodes:
let chart = new OrgChart("#tree", {
nodeBinding: {
field_0: "name",
icon: "icon"
},
nodes: [
{ id: "1", name: "Amber McKenzie", icon: "face" },
]
});Explanation
nodeBinding maps the icon property to the icon template field. The nodes array contains node objects with an icon property that specifies the Material Icon name.
This method allows easy customization by changing the icon value in the nodes array.
Conclusion
By using foreignObject, you can integrate Material Icons or any other HTML into OrgChart JS nodes. This approach provides a flexible way to enhance organizational chart visualization.
Now you can experiment by adding different Material Icons, or any other HTML, to your OrgChart JS nodes.