Getting & ldquo; TypeError: document.getElementById (& hellip;) is null & rdquo; when using reac.js with chart.js

advertisements

I am using react and chart.js together to plot bar chart. But in chart.js we have to use canvas tags and to find that tag and to place bar chart in it we use our normal document.getElementById() method. I tried lots of combinations like putting document.getElementById() at the beginning, or inside a $(document).ready(), even within react's componentDidMount() method. But Still I am getting "TypeError: document.getElementById(...) is null". If anyone know about it, please give me a suggestion. Thank You.

Here is the code which I am trying to execute:

var React = require("react");

var Chart = React.createClass({

    getDefaultProps: function() {
        barChartData = {
            labels : ["Option1", "Option2"],
            datasets : [
                {
                    fillColor : "rgba(220,220,220,0.5)",
                    strokeColor : "rgba(220,220,220,0.8)",
                    highlightFill: "rgba(220,220,220,0.75)",
                    highlightStroke: "rgba(220,220,220,1)",
                    data : [65, 35]
                }
            ]
        }
    },

    onload: function() {
        console.log(document.getElementById('canvas_poll'));
        var ctx = document.getElementById("canvas_poll").getContext("2d");

        window.myBar = new Chart(ctx).HorizontalBar(this.props.barChartData, {
            responsive : true,
        });
    },

    componentDidMount: function() {
        this.onload();
    },

    render: function() {

        return (
            <div>
                <canvas classID="canvas_poll" height={100} width={600}></canvas>
            </div>
        );
    }

});

module.exports = Chart;


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>