I am working with the d3-org-chart library to create an organizational chart, and I'm encountering an issue where I want to automatically expand the root level and the next two levels (levels 0, 1, and 2) upon initial render. However, I'm struggling to achieve this.
Here's the relevant part of my code:
import * as d3 from 'd3';
import {OrgChart} from "d3-org-chart";
export function initializeOrgChart(usersData) {
const formattedData = transformDataForOrgChart(usersData);
const container = document.querySelector('.chart-container');
if (container) {
const orgChart = new OrgChart()
// ... other configurations ...
.container('.chart-container')
.data(formattedData)
.render();
// Assuming formattedData[0] is the root element of the org chart
expandSpecificLevels(formattedData[0], 0, 2, orgChart);
}
}
function transformDataForOrgChart(users) {
return users.map(user => {
return {
customId: user.id,
customFullName: user.fullName,
customEmail: user.email,
customJob: user.job,
customLocation: user.location,
customPicture: user.picture ? user.picture : null,
customParentId: user.managerId
};
});
}
// Example function to expand specific levels - not working as expected
function expandSpecificLevels(node, currentLevel, maxLevel, orgChart) {
if (currentLevel <= maxLevel) {
orgChart.expand(node);
if (node.children && node.children.length > 0) {
node.children.forEach(childNode => {
expandSpecificLevels(childNode, currentLevel + 1, maxLevel, orgChart);
});
}
}
}
I’ve tried to use a recursive function expandSpecificLevels to expand the nodes, but it doesn’t seem to work. The chart renders without expanding the specified levels. I also attempted to use setTimeout to delay the expansion after render, but it had no effect.
Could someone help me understand how to correctly expand specific levels in d3-org-chart upon initial render? Any insights or alternative approaches would be greatly appreciated.
you want to expand some levels (2) at initial render so use the settings of .initialExpandLevel
chart = new d3.OrgChart()
.initialExpandLevel(2)
:
:
and you'll have the result waited..
you could see the impact of this parameter here