Skip to content

Instantly share code, notes, and snippets.

@Youngestdev
Created February 15, 2019 04:23
Show Gist options
  • Select an option

  • Save Youngestdev/5f41ab6afc0d4f7f3a6898e671293594 to your computer and use it in GitHub Desktop.

Select an option

Save Youngestdev/5f41ab6afc0d4f7f3a6898e671293594 to your computer and use it in GitHub Desktop.
Actually, messing around unethical ideas and sketching rough codes.
import React, { useEffect, useContext, useRef } from 'react';
export const NodeMounter = props => {
const ref = useRef('');
const { node } = props;
ref.appendChild(node);
useEffect(( {node: prevNode} ) => {
const { node } = props;
ref.current.removeChild(prevNode);
ref.current.appendChild(node);
return () => {
const { node } = props;
ref.current.removeChild(node);
}
});
return <g ref={ref} />;
};
export const RoughContext = React.createContext();
@Youngestdev
Copy link
Copy Markdown
Author

Still learning how to write hooks. Sadly, I wrote this ( pardon me if it's bad code, I fore apologise ): Anyways, here is the ReactRough component. But, test doesn't pass 😢 . The reason the test doesn't pass is because there's smtn I'm not doing right in the Context Consumer-Provider API.

const ReactRough = (props, rc, ctx, rendererRef)  => {

    const { renderer, width, height, backgroundColor } = props;

    const forceUpdate = useForceUpdate();

    rendererRef = useRef();

    useEffect(() => {
        const { renderer } = props;
        ctx =
            renderer === 'canvas' && rendererRef.current.getContext('2d');
        rc = Rough[renderer](rendererRef.current);
        // TODO: this.forceUpdate();
        forceUpdate();
    }, []);


    const clearCanvas = () => {
        const { backgroundColor, width, height } = props;
        // If this is the first render the ctx will be null
        // It will be cleared later in the useEffect arc
        if ( !ctx ) {
            return;
        }

        if ( backgroundColor ) {
            ctx.save();
            ctx.fillstyle = backgroundColor;
            ctx.fillRect(0, 0, width, height);
            ctx.restore();
        } else {
            ctx.clearRect(0, 0, width, height);
        }
    };

    const redraw = () => forceUpdate();

    // let children = props.children;


    const rendererOptions = {
        width,
        height
    };

//    First clear the canvas in case of a new render.
    if ( renderer === 'canvas') {
        clearCanvas();
    } else {
        rendererOptions.style = { backgroundColor };
    }

    const Renderer = renderer;

    return (
        <RoughContext.Provider value={{ rc: rc, renderer}}>
            <Renderer {...rendererOptions} ref={rendererRef}>
                {props.children}
            </Renderer>
        </RoughContext.Provider>
    );

};

@Youngestdev
Copy link
Copy Markdown
Author

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment