Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Pass down a canvas ref through Context in React

Tags:

reactjs

canvas

I am working on implementing some canvas rendering by using Components. I have the following Component which attempts to layout the canvas to the page, and have subcomponents in the Stage component draw to its context.

I need a reference to the canvas elements that my Renderer component is rendering. So I ask for the ref in the JSX, and set it on my component when I get it. I'm also using React context, so that all the children components can access this canvas reference. The problem I'm having is that it seems getChildContext is called before the canvas ref is assigned and so all the children component access an undefined canvas and no drawing is done.

export default class Renderer extends React.Component {

    static childContextTypes = {
        canvas: PropTypes.object
    };

    getChildContext() {
        console.log("get child context")
        return { canvas: this.canvas };         
    }

    render() {

        return (
            <div className="CanvasHolder" key={0}>
            <canvas className="MainCanvas" ref= { 
                canvas => { 
                    this.canvas = canvas 
                    console.log("got ref");

                }
                } />
            <Stage />
            </div>
            )
    }
}
like image 582
Alex Bollbach Avatar asked Aug 21 '17 03:08

Alex Bollbach


People also ask

How do you pass down ref React?

React will pass the ref through and forward it down to <input ref={ref}> by specifying it as a JSX attribute. When the ref is attached, ref. current will point to the <input> DOM node. The second ref argument in the InputRef component only exists when you define a component with React.

Can you pass state down React?

Passing state as props from parent to child components is a core concept of React. By keeping state in only a few components and passing it to as many children as needed in the form of props, you will be able to write code that is easier to maintain, and you will thank yourself down the road.


Video Answer


1 Answers

You can access the ref only after in componentDidMount (after it is rendered). But the parent component is considered rendered only when all of its children are rendered. So children can't access parent's ref before it is rendered. Instead of returning canvas ref directly, try to pass custom function getCanvas() instead:

getCanvas = () => {
  return this.canvas
}

And then in your children component call this function to retrieve canvas ref.

like image 105
GProst Avatar answered Sep 22 '22 18:09

GProst