Daniel Nalesnik
Daniel Nalesnik

Reputation: 55

Is there a way to determine the current font-size of a DOM element in ReactJS?

In our app, a piece of text changes font-size using a CSS class with responsive breakpoints.

But some users want fine-tooth control over the font-size, so we have "increase" and "decrease" font size buttons.

Using React, I have:

const [characterSize, setCharacterSize] = useState(45);

and

function increaseCharacterSize() {
  setCharacterSize(characterSize + 1);
}
<div
  style={{ fontSize: `${characterSize}px` }}
  className="myClass"
  >Our awesome text</div>

Calling increaseCharacterSize increase the font size as expected.

The problem is, I don't want to set the characterSize to "45" as per the example, because the starting size (from which to start incrementing/decrementing from) is dependent on the current fontSize of the element in the DOM (which is based on the CSS class which is based on the browser window).

I need to be able to determine the DOM element's current rendered fontSize. In plain vanilla javascript, this would look something like:

window.getComputedStyle(el, null).getPropertyValue('font-size');

Is there any way to do this in React?

Upvotes: 1

Views: 3036

Answers (2)

Dennis Vash
Dennis Vash

Reputation: 53874

Get the ref and call your desired function:

export default function App() {
  const inputRef = useRef();

  useEffect(() => {
    const size = window
      .getComputedStyle(inputRef.current, null)
      .getPropertyValue("font-size");

    console.log(size);
  }, []);

  return (
    <div className="App">
      <div ref={inputRef} style={{ fontSize: 45 }}>
        Our awesome text
      </div>
    </div>
  );
}

https://codesandbox.io/s/cranky-tharp-ldexxr?file=/src/App.js:67-439

Upvotes: 4

Laurenz Honauer
Laurenz Honauer

Reputation: 344

I think there are two parts to this:

  1. as @super claims, you can simply use vanilla javascript in react.

  2. What is the reason you want to take control over the font size in your app's code?

Normally you would do this by using rem. It is a size unit you can use in your CSS that will automatically scale in size as the user changes the font size setting in the browser. So basically this is a wheel that already exists and you want to re-invent.

Upvotes: 0

Related Questions