Amchart HTML container not found (React)

Luke Sikuade picture Luke Sikuade · Dec 12, 2018 · Viewed 7.6k times · Source

EDIT 1 (initial): It appears that setState() callback isn't working the way I'd expect it to. For example:

this.state = {table: true}
this.setState({table: false}, ()=> console.log(this.state.table)); 

Will log out 'true', when I'd expect it to log out false.

EDIT 2: I believe there is something wrong with how I'm handling my drop down requests and that may be causing the bulk of my issues. So I'm going to mark this as solved, because Dileep's solution should work. I will update this in a couple of hours with my result.

EDIT 3(Final): I was using a switch() statement that was somehow triggering multiple cases and resetting my state.

I think I understand what the problem is, however, I'm not entirely sure how to solve it.

I want to conditionally render an element before it can be accessed by Amchart's create("elementID", chartType) function. I hope to render on dropdown by calling the following function:

loadBarChart() {
this.setState({ piechart: false, table: false, barchart: true });
var chart = am4core.create("barChartDiv", am4charts.XYChart);
chart.data = this.state.data;

let categoryAxis = chart.xAxes.push(new am4charts.CategoryAxis());
categoryAxis.dataFields.category = "schoolname";
categoryAxis.title.text = "Schools";

let valueAxis = chart.yAxes.push(new am4charts.ValueAxis());
valueAxis.title.text = "Number of Students";
}

And the barChartDiv is displayed as such:

 {this.state.barchart && (
      <section>
        <h1 style={{ textAlign: "center" }}>School Data</h1>
        <div id="barChartDiv" style={{ width: "100%", height: "500px" }} />
      </section>
 )}

When I select drop down, I am told that barchart is false, and then true after the following error:

Instance.js:128 Uncaught Error: html container not found

Because setState() often doesn't update immediately. I've tried going around this by including the loadBarChart() code in the setState() callback function, but I get the same errors as before. So what I'm almost certain is happening is that am4core.create() is looking for an element with id "barChartDiv" before that element is rendered, and so I get an html container not found error.

What's the best way of dealing with this, short of using css?

Answer

Akber Iqbal picture Akber Iqbal · Jan 11, 2019

I got this error in plain HTML/JS.

At time of error, i had added the <script> section before my <div id="chartdiv"></div>

resolution was to place the <script> section after <div id="chartdiv"></div>

Writing this here to help anyone who might run into this themselves.