Carlos Escobar
Carlos Escobar

Reputation: 434

strange behaviour in my code using react hooks

This might sound silly, but I'm trying to understand my own code and I wanted to see your input here. I'm using useRef() to click a HTML element on user changing the screen. For some reason the ref.current passes the if condition I created so it only executes if this isn't null. Not sure why? I managed to make it work but I had to add an additional if statement to the onresize function, could someone explain why this is the case.

import React, { useRef, useEffect } from 'react';
import classes from './Backdrop.css';

const backdrop = (props) => {
    const backDropRef = useRef(null);
    useEffect(() => {

        if (backDropRef.current !== null && props.show) {
            document.body.onresize = () => {
                if (backDropRef.current !== null) {
                    backDropRef.current.click();
                }
            };
        }
    }, [backDropRef.current, props.show]);

    let classForBackdrop = classes.Backdrop;

    if (props.toolTipShow) {
        classForBackdrop = classes.BackdropForToolTip;
    }

    return props.show ? (
        <div
            ref={backDropRef}
            className={classForBackdrop}
            onClick={props.clicked}
            id="back-drop"
        ></div>
    ) : null;
};

export default backdrop;


Upvotes: 0

Views: 72

Answers (1)

buzatto
buzatto

Reputation: 10382

I will break into parts:

  • on true at if conditional it attaches onresize listener that has backDropRef.current.click();
  • backDropRef.current points to your div;
  • once show prop turns to false div is removed from DOM;
  • backDropRef.current lost div reference, and now is null;

After all this, you need the if condition because otherwise any resize event triggered when show is false there is no <div>, backDropRef.current is null and you try to call click on a null value which throws an error.

Upvotes: 1

Related Questions