How to respond to the width of an auto-sized DOM element in React?

To respond to the width of an auto-sized DOM element in React,m we can use the react-measure hook.

To install it, we run

npm i react-measure

Then we use it by writing

import * as React from "react";
import Measure from "react-measure";

const MeasuredComp = () => (
  <Measure bounds>
    {({
      measureRef,
      contentRect: {
        bounds: { width },
      },
    }) => <div ref={measureRef}>My width is {width}</div>}
  </Measure>
);

to use the Measure component from react-measure to retuen the width of the div by assigning the measureRef provided as the value of the div’s ref prop.