简体   繁体   中英

Cannot use npm module react-chartjs with React

I'm new to npm and React. I have an application that uses a React UI and I want to include some charts using react-chartjs .

In my app.jsx file I try to create a bar chart:

var BarChart = require("react-chartjs").Bar;
var chartData = {
    ...
};

var CategorySummaryGraph = React.createClass({
  render: function() {
    return (
        <BarChart data={chartData} width="600" height="250"/>
    );
  }
});

I bundle using gulp and browserify:

var gulp = require('gulp');
var react = require('gulp-react');
var browserify = require('gulp-browserify');

gulp.task('bundle-jsx', function() {
  return gulp.src('./myapp/static/jsx/*.jsx')
      .pipe(react())
      .pipe(browserify())
      .pipe(gulp.dest('./myapp/static/js/'));
});

This gives me an error when loading the page in the browser:

Uncaught Error: Invariant Violation: addComponentAsRefTo(...): Only a ReactOwner can have refs. This usually means that you're trying to add a ref to a component that doesn't have an owner (that is, was not created inside of another component's `render` method). Try rendering this component inside of a new top-level component which will hold the ref.
invariant @ react.js:18405
ReactOwner.addComponentAsRefTo @ react.js:13256
attachRef @ react.js:14174
ReactRef.attachRefs @ react.js:14190
attachRefs @ react.js:14051
assign.notifyAll @ react.js:1045
ON_DOM_READY_QUEUEING.close @ react.js:13934
Mixin.closeAll @ react.js:16693
Mixin.perform @ react.js:16634
batchedMountComponentIntoNode @ react.js:11998
Mixin.perform @ react.js:16620
ReactDefaultBatchingStrategy.batchedUpdates @ react.js:9140
batchedUpdates @ react.js:14853
ReactMount._renderNewRootComponent @ react.js:12133
ReactPerf.measure.wrapper @ react.js:13366
ReactMount.render @ react.js:12222
ReactPerf.measure.wrapper @ react.js:13366
(anonymous function) @ myapp.js:23474
m.Callbacks.j @ jquery-1.11.3.min.js:2
m.Callbacks.k.fireWith @ jquery-1.11.3.min.js:2
m.extend.ready @ jquery-1.11.3.min.js:2
J @ jquery-1.11.3.min.js:2

From the error message it seems to me like the BarChart doesn't have a render method... which obviously can't be the case if react-chartjs works at all. I'm not sure where to go with this so any help would be much appreciated.

I had been defining React by including it on my html page:

<script src="https://cdnjs.cloudflare.com/ajax/libs/react/0.13.0/react.js"></script>

What fixed the problem was requiring it instead in my .jsx file:

 var React = require("react");

Not sure why this worked but from reading around, perhaps there were multiple initializations and/or definitions of React that were causing conflicts.

Thanks @Daniel for pointing me in the right direction.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM