Get height of ant design component using ref.current.clientHeight is `undefined`

Viewed 487

I'm trying to detect the change in the height of an ant design <Row> component However, when I added a reference to it and tried to get the clientHeight of ref.current.clientHeight, I get an undefined value

Any idea how can I get the height of an antd element? I can add a parent wrapper to the antd component but I don't want to do that... I need to access the inner DOM of the component

Codesandbox: https://codesandbox.io/s/vigilant-gates-jq46u?file=/index.js

import React, { useEffect, useRef } from "react";
import ReactDOM from "react-dom";
import "antd/dist/antd.css";
import "./index.css";
import { Card } from "antd";

const App = () => {
  const ref = useRef(null);

  useEffect(() => {
    console.log("height", ref?.current?.clientHeight);
  }, []);

  return (
    <div>
      <Card title="Test" style={{ width: 300 }} ref={ref}>
        <p>Card content</p>
        <p>Card content</p>
        <p>Card content</p>
      </Card>
    </div>
  );
};
ReactDOM.render(<App />, document.getElementById("container"));
1 Answers

Since Card is a functional component and antd doesn't implement this component by React.forwardRef, actually you can't access the card dom element by passing ref, as an alternative you can set an id on the Card component and try to get the DOM node by document.getElementById, like this:

const App = () => {
  const ref = React.useRef(null);

  React.useEffect(() => {
    ref.current = document.getElementById('myCard');
    console.log("height", ref.current.clientHeight);
  }, []);

  return (
    <div>
      <Card title="Test" style={{ width: 300 }} id="myCard">
        <p>Card content</p>
        <p>Card content</p>
        <p>Card content</p>
      </Card>
    </div>
  );
};

another solution colud be, to assign the ref on the parent of Card component, like this:

const App = () => {
  const ref = React.useRef(null);

  React.useEffect(() => {
    console.log("height", ref.current?.clientHeight);
  }, []);

  return (
    <div ref={ref}>
      <Card title="Test" style={{ width: 300 }}>
        <p>Card content</p>
        <p>Card content</p>
        <p>Card content</p>
      </Card>
    </div>
  );
};
Related