sunburst-chart
sunburst-chart copied to clipboard
How to add custom behaviour on click event of any slice of sunburst component in react?
When sunburst component is used in react built with react-kapsule
, how can I add custom behaviour on click event of any slice of sunburst.
From suggestion here, I tried something like this:
<ReactSunburst
//...
data={data}
onClick={(node) => {
myChart.focusOnNode(node);
console.log("clicked");
}}
/>
The problem I faced is that myChart
is undefined inside the onClick
handler of react component. So, this gives myChart is not defined
error and the chart does not perform the default zooming behavior. If I omit the first line, "clicked" gets printed to the console.
Link to the errored line is the codesandbox.
Sorry, I just realized that we have to add the methods to methodNames
array. So I tried this:
const ReactSunburst = fromKapsule(SunburstChart, {
methodNames: ["onClick"]
});
<ReactSunburst
width={200}
height={200}
excludeRoot
label="name"
size="size"
color={(d, parent) => null}
tooltipContent={(d, node) => `Size: <i>${node.value}</i>`}
data={flare}
onClick={(entry) => {
console.log("Hello from inside onClick handler!!");
}}
/>
Now clicking on slices zooms in as desired. However, it does not seem to invoke the onClick
handler at all as the message Hello from inside onClick handler!!
is not printed to the console. Here is the link to this codesandbox.
And when I we omit methodNames
, the message gets printed, but the slice does not zooms in. Here is the link to sandbox with this change.
It will be of great help to find one working example of react-capsule + sunburst-chart with click event handler.
@RajS999 thanks for reaching out.
onClick
is not a component method, it's a prop. Thus you shouldn't include it in methodNames
.
The real issue is that by defining onClick
you override the default behavior which is to zoom onto the node. That is done via the focusOnNode
method (this one yes, needs to be included in your methodNames
list). So all you need to do is include that action on your onClick
implementation, like so:
onClick={node => {
myChartRef.current.focusOnNode(node);
// add your custom onClick functionality here
}}
This assumes myChartRef
is a React forward ref of your component (normally set up via useRef
). But we're really into React domain at this point. 😄
@vasturiano I am trying to use the sunburst using useEffect hook and on adding onClick function it shows myChartRef.current.focusOnNode(node) is not a function
@vasturiano @RajS999
I am still witnessing myChartRef.current.focusOnNode(node) is not a function error.
if Possible, Can anyone pls share sample code for using in react with react kapsule and forward ref. Just the syntax would do
Thanks.