Ad

React Canvas Context Gets Over Written In ComponentDidMount

- 1 answer

I am generating components from an array and each component has canvas elements that I want to grab the context from using componentDidMount. It works, but only if I have one component. If you look at my full codepen example, the context gets overwritten after each component is loaded and only captures the context of the last component.

How can I grab the context from each component and assign it to a value so that I can manipulate it in the parent component?

It makes more sense by looking at the demo

var outputs = [
  { name: 'output1' },
  { name: 'output2' },
  { name: 'output3' }
];

var App = React.createClass({
  render: function() {
    return (
      <div>
        {outputs.map(function(output) {
         return <ColorPickerContainer id={output.name} />
        })}
      </div>
    );
  }
});

var ColorPicker = React.createClass({
  getInitialState: function() {
    return {
      color: rgbColor
    }
  },
  componentDidMount: function() {
  rgbColor
    }
  },
  componentDidMount: function() {
    var canvasB = this.refs.canvasBlock;
    var canvasS = this.refs.canvasStrip;
    ctxB = canvasB.getContext('2d');
    ctxS = canvasS.getContext('2d');
    this.props.blockFill(ctxB);
    this.props.stripFill(ctxS);
  },
  render: function(e) {
    var styles = {
      opacity: this.props.isVisible ? '1' : '0'
    };
    return(
      <div id="color-picker" style={styles} className={this.props.id}>
        <canvas id="color-block" 
                height={hB} 
                width={wB} 
                onMouseDown={this.props.mouseDownBlock}
                onMouseMove={this.props.mouseMoveBlock}
                onMouseUp={this.props.mouseUpBlock}
                ref="canvasBlock"></canvas>
        <canvas id="color-strip" 
                height={hS} 
                width={wS} 
                onClick={this.props.clickStrip}
                ref="canvasStrip"></canvas>
      </div>
    );
  }
});
Ad

Answer

In this case (I think?), Ideally the component that created the canvas, should be handling its own colorization, and interactions... and handling its own context. Since the context you created are sitting in the global space, they're getting overridden with each new creation, rather than sitting within their class.

Here's a version which passes those contexts up to the ColorPicker class - http://codepen.io/tholman/pen/a3ef6cff6022bc1eaa44e5495a4e32dc/?editors=001, where the coloring is happening.

I'm not really great with react, so there might be a "react" way of doing this... but this'd let me sleep at night.

Ad
source: stackoverflow.com
Ad