Problem:
I have this class component and i want to convert it in a functional component, how can I do? I tried to do it but i have some issue whit the this.chart properties in the componentDidMount()
method, where i have to put it in functional component? I also tried to use the hook useRef()
in the place of createRef()
is it correct? Anyone can provide me a full converted example so i can understand how to do it? Thank you
import React, { Component } from 'react';
import OrgChart from '@balkangraph/orgchart.js';
export default class Chart extends Component {
constructor(props) {
super(props);
this.divRef = React.createRef();
}
shouldComponentUpdate() {
return false;
}
componentDidMount() {
this.chart = new OrgChart(this.divRef.current, {
nodes: this.props.nodes,
nodeBinding: {
field_0: 'name',
img_0: 'img',
},
});
this.chart.on('init', function () {
console.log('init');
});
this.chart.on('click', function () {
console.log('click');
});
}
render() {
return <div id="tree" ref={this.divRef}></div>;
}
}
Solution:
It’s not that much different really.
The main thing is the use of the React.useEffect
..
Also note, in your above your not doing anything with chart on component unmount, if you return a function from useEffect
you can use that to cleanup on unmount. Also note the need for this
is now gone..
Below is your code converted. E&OE
import React, { useEffect } from 'react';
import OrgChart from '@balkangraph/orgchart.js';
export default function Chart(props) {
const divRef = React.createRef();
useEffect(() => {
const chart = new OrgChart(divRef.current, {
nodes: props.nodes,
nodeBinding: {
field_0: 'name',
img_0: 'img',
},
});
chart.on('init', function () {
console.log('init');
});
chart.on('click', function () {
console.log('click');
});
}, []);
return <div id="tree" ref={divRef}></div>
}
As pointed out above your current code is not doing anything about unmounting the component, often things like chart components have a destroy method etc, looking at the docs for OrgCharts if it’s the same -> https://balkan.app/OrgChartJS/API/classes/OrgChart#destroy
So to really finish the component off,. I would put this in the useEffect
hook
useEffect(() => {
const chart = ....
....
return () => {
chart.destroy();
}
},[]);