Reputation: 917
I guess I really don't get the concept. I want to create a custom object inside a react component. The custom objects itself creates new elements.
For example: I have a custom object
function LabelEditor(canvas, width, height) {
this.canvas = canvas;
this.canvas.width = width;
this.canvas.height = height;
this.canvas.id = 'mainEditor';
this.canvas.getContext('2d');
console.log('hi ' + this.canvas.width + ' / ' + this.canvas.height);
this.getCanvas = function() {
return this.canvas;
};
}
Now I want to access the properties, functions and the elements created by this object inside a react component, something like this:
var Editor = React.createClass({
render: function() {
return (
<div>{this.props.editor.getCanvas()}</div>
);
}
});
React.render(
<Editor editor={new LabelEditor(React.DOM.canvas, 500, 500)} />,
document.getElementsByTagName('editor')[0]
);
But every combination of props, state and something have failed by now.
The idea behind this is, I want to build an editor with fabric.js, but want to use it inside a React.js
application. The fabric.js
functionality will be wrapped inside a custom object with an interface to control the actions. I want to use React only as the visual part, the LabelEditor
-object will as a controller, and the the fabric.js
as some sort of model, providing a drawable canvas.
Upvotes: 1
Views: 4837
Reputation: 2577
Below is how I would structure the code (See this JSBin for a working demo). Basically, Editor component renders <canvas>
and you would instantiate your LabelEditor in componentDidMount()
. You use React.findDOMNode()
because <canvas>
in render()
represents a virtual DOM and you would need to find the corresponding DOM. Now, LabelEditor
can do the drawing.
function LabelEditor(canvas, width, height) {
this.canvas = canvas;
this.canvas.width = width;
this.canvas.height = height;
this.canvas.id = 'mainEditor';
// Draw something
var ctx = this.canvas.getContext('2d');
ctx.fillStyle = "#A0EBDD"
ctx.fillRect(30, 30, 150, 150);
}
var Editor = React.createClass({
componentDidMount: function() {
var canvas = React.findDOMNode(this.refs.canvas);
this._editor = new LabelEditor(canvas, this.props.width, this.props.height);
},
render: function() {
return (
<canvas ref="canvas"></canvas>
);
}
});
React.render(
<Editor width={500} height={500} />,
document.getElementById('editor')
);
Upvotes: 4