Search code examples
reactjsreact-hooksantduse-refant-design-pro

How to get DOM reference of Ant design components in react


I am using Ant design components. I need to get 'ref' of Image component, but it doesn't support 'ref' property.

I am trying to do this.

const ImageRef = useRef(null)

<Image ref={ImageRef} />

Is there any alternate way?


Solution

  • You can try the following code, by wrapping the <Image/> component inside <span>

    import React, { useRef } from "react";
    import "antd/dist/antd.css";
    import "./index.css";
    import { Image } from "antd";
    
    const App = () => {
      const ImageRef = useRef(null);
    
      const display = () => {
        console.log(ImageRef.current.children[0].children[0].naturalHeight);
        console.log(ImageRef.current.children[0].children[0].naturalWidth);
      };
      return (
        <span ref={ImageRef}>
          <Image
            onClick={display}
            width={200}
            src="https://gw.alipayobjects.com/zos/antfincdn/aPkFc8Sj7n/method-draw-image.svg"
          />
        </span>
      );
    };
    
    export default App;
    

    Note:

    console.log(ImageRef.current);
    

    gives

    screenshot

    So if you want image offsetHeight and offsetWidth / naturalHeight and naturalWidth you need to do the following

    console.log(ImageRef.current.children[0].children[0].naturalHeight);
    

    I hope this helps you!