Categories
React Answers

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

Spread the love

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.

By John Au-Yeung

Web developer specializing in React, Vue, and front end development.

Leave a Reply

Your email address will not be published. Required fields are marked *