Ad

React Component Reference Own DOM-element In Typescript

- 1 answer

Still being quite new to React I've run across the following issue: I'm creating a component this way:

export const CSpiderWeb = (props: iSpiderWebProps) => {
    const classes = useStyles();
    const [drawingObject, setDrawingObject] = useState({} as iDrawingObject);

    const _InitRaphael = (target : HTMLDivElement) => {
        while (target.firstChild) {
            target.removeChild(target.firstChild);
        }

        const workDrawingObject : iDrawingObject = {
            width : target.offsetWidth,
            height : target.offsetHeight,
            centerX : target.offsetWidth / 2,
            centerY : target.offsetHeight /2
        }

        workDrawingObject.paper = Raphael(target, workDrawingObject.width, workDrawingObject.height);

        setDrawingObject(workDrawingObject);
    }


    var workRef = createRef<HTMLDivElement>();
    _InitRaphael(workRef.current as HTMLDivElement);

    return <div ref={workRef} className={classes.paperContainer}>{drawingObject.centerX}x{drawingObject.centerY}</div>
}

What I'm trying to accomplish here is get the rendered DIV element and pass it to the _InitRaphael method, but it appears that this is called before the element is rendered. Makes sense, but HOW could this be done. I've googled and googled and sometimes I run across the componentDidMount hook, but can thhat be used here and if thats the case then how?

Ad

Answer

You can't use componentDidMount because it could only be used in class components, when you use function component as in your example use hookshttps://reactjs.org/docs/hooks-effect.html

I would recommend you to use the useEffect hook which imitates componentDidMount.

Ad
source: stackoverflow.com
Ad