Chartjs-Getting "TypeError: document.getElementById(…) is null" when using react.js with chart.js

2👍

I had a similar problem with a react web app I was building. In addition to what was said in the previous solution, there are a few things I think you might find helpful based on what I read in the comments.

Script is ran before the element actually exists

One common problem is that the element does not exist at the time of rendering.

for example if your HTML looked like

    <script src="**your file **" type="text/babel"></script>
    <div id="canvas_poll"></div>

then your script would be ran before the div with the id you are looking for could get rendered.
However, when switched, the script is ran after the div is formed.

    <div id="canvas_poll"></div>
    <script src="**your file **" type="text/babel"></script>

That way, the element that the script is looking for actually exists and can be found.

Some solutions to this are listed in this link Why does jQuery or a DOM method such as getElementById not find the element?

Change <div /> to <div></div>

In my case, I was still getting null from my getElementById method after running the script after the div was formed. It ended up being how the target divs were set up.

I’m not sure why, but when my target div looked like

    <div id= "target1"/>
    <script src="target1.jsx" type="text/babel"></script>

I could render to that container using react. However, if I tried to render a second react element:

    <div id= "target1"/>
    <script src="target1.jsx" type="text/babel"></script>
    <div id= "target2"/>
    <script src="target2.jsx" type="text/babel"></script>

The first react element would show up but the second would not.
What I did to fix it was change the div formatting from

     <div id="target"/>

to

     <div id="target></div>

on all the target divs.

After I made that change, all my react elements came in fine. I’m not sure why it worked that way, but I hope it is helpful.

1👍

The document.getElementById() uses an element’s ‘ID’ attribute, not ‘classID’ (which is also unsupported by the ‘canvas’ tag). Try adding id="canvas_poll" to the canvas element like so:

<canvas id="canvas_poll" height={100} width={600}></canvas>

Leave a comment