0

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?

2 Answers 2

1

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

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

Sign up to request clarification or add additional context in comments.

1 Comment

Both answers are similar so I'm tagging the first one as correct.
1

You should consider using the useEffect hook. It called after the rendering done so the ref should have value.

useEffect(() => {
  _InitRaphael(workRef.current as HTMLDivElement);
}, [])

But unless you use an external non React library, you should not use this pattern. In a React app ref usage is the exception, not the normal way of dooing things.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.