Home > Mobile >  UseRef only returns me undefined or null
UseRef only returns me undefined or null

Time:03-15

Im trying to get the img element to be printed on the console but for some reason the only thing i get is undefined and null. This is my code:

import CardContent from '@mui/material/CardContent';
import CardActions from '@mui/material/CardActions';
import UIButton from 'app/main/components/UIButton';
import { useRef, useEffect } from 'react';

function ExpandImageDialog({ open, onClose: close, url }) {
  const refInput = useRef();

  const styleImage = () => {
    console.log(refInput.current, 'it got here');
  };

  useEffect(() => {
    styleImage();
  }, [open]);

  return (
    <Modal open={open} onClose={close}>
      <Card className="px-20 pt-6 pb-32" sx={modalStyle}>
        <CardHeader title="Visualização de imagem" />
        <hr />
        <CardContent>
          <img
            className="flex-img"
            loading="lazy"
            src={url}
            alt="Documento"
            style={imageStyle}
            ref={refInput} />
        </CardContent>
        <CardActions className="justify-end">
          <UIButton onClick={close}>Voltar</UIButton>
        </CardActions>
      </Card>
    </Modal>
  );
}

this is what it shows on the console

Im new to react so sorry if im doing something obviously wrong

Thank you for the help!

CodePudding user response:

Your code looks correct.

It is null because you are logging the ref in the useEffect with a dependency on open. This would be running when the component is mounted.

If you try the following with refInput as a dependency, you should see the ref log.

    useEffect(()=>{
        console.log(refInput.current, 'it got here');
    }, [refInput])

CodePudding user response:

The way you are using your ref is correct, see this repro for a simple reproduction. Here is the code :

import React from 'react';
import { render } from 'react-dom';

let renderCount = 0;

const App = () => {
  const [isVisible, setIsVisible] = React.useState(false);
  const imgRef = React.useRef();

  const styleImage = () => {
    console.log('img ref = ', imgRef.current);
  };

  const handleClick = () => {
    setIsVisible(!isVisible);
  };

  React.useEffect(() => {
    styleImage();
  }, [isVisible]);

  renderCount  = 1;
  return (
    <div>
      <div>render count = {renderCount}</div>
      <button onClick={handleClick}>{isVisible ? 'Hide' : 'Show'} image</button>
      <br />
      <CustomImg isVisible={isVisible}>
        <img src="https://picsum.photos/200/300" ref={imgRef} />
      </CustomImg>
      <br />
    </div>
  );
};

// Same as your Modal component
const CustomImg = ({ isVisible, children }) => {
  if (!isVisible) return <></>; // Component returns nothing, so img isn't known. Therefore, ref is undefined on the first render.
  return <div>{children}</div>;
};

render(<App />, document.getElementById('root'));

The problem comes from the prop open/close that you pass to the Modal component. If it is not rendered, then your ref will stay undefined. The null status surely comes from your Modal as well. In my example, try to show and then hide the image, you will see that the ref is null after you hide it, which is normal. There is a re-render, so the ref is reset as well.

Note that I created the variable renderCount outside of the component, so it is a global variable that you can use to check how many times your component re-render. Try doing it to see what happen.

  • Related