reactjsamchartsamcharts5

Amcharts5 - Error You cannot have multiple Roots on the same DOM node - React 17


I want to create a chart with amcharts5 in my react app.

I instantiate a root element of amcharts5 in a component that I import in my app component. I get the following error

You cannot have multiple Roots in the same DOM node

Here's my version:

"react": "^17.0.2"
"@amcharts/amcharts5": "^5.1.1"

Here's my code:

import { useLayoutEffect } from 'react'
import * as am5 from '@amcharts/amcharts5'

export default function AmCharts5() {
  useLayoutEffect(() => {
    let root = am5.Root.new('chartdiv')

    // root.current = root
    // here is a second Error : Property 'current' does not exist on type 'Root'


    return () => {
      root.dispose()
    }
  }, [])

  return <div id="chartdiv" style={{ width: '100%', height: '500px' }}></div>
}

Solution

  • I had the same error, when I created second root element for my chart legend, but forgot to add the dispose method for this root element in useEffect return function. So in my case I solve this error by adding second dispose method in useEffect return function.

    In my case useEffect has dependence on some data, and when I change it, useEffect runs again, and try to create second root element with the same name. And at after first render when I change someVar I have this error.

    before:

    useEffect(() => {
        const root = am5.Root.new("chart-pop");
        // ... some code
    
        const legendRoot = am5.Root.new("legend-div");
        // ... some code
    
        return () => root.dispose();
    }, [someVar]);
    

    After:

    useEffect(() => {
        const root = am5.Root.new("chart-pop");
        // ... some code
    
        const legendRoot = am5.Root.new("legend-div");
        // ... some code
    
        return () => {root.dispose(); legendRoot.dispose();};
    }, [someVar]);