How to Add Material Icons in OrgChart JS Nodes Using ForeignObject
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'll walk through how to achieve this using the foreignObject
element
Here is the code example
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 will load 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, we 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 us to use regular HTML elements inside an 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 we defined earlier.
The nodes
array contains node objects with an icon
property specifying the Material Icon name.
This method allows for easy customization by changing the icon value in the nodes array.
Conclusion
By using foreignObject
, you can seamlessly integrate Material Icons or any other HTML into OrgChart JS nodes. This approach provides a flexible way to enhance the visualization of your organizational charts.
Now, you can experiment by adding different Material Icons or any other HTML to your OrgChart JS nodes!
Material Icon - OrgChart JS