Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

159
Views
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?

about 4 years ago · Juan Pablo Isaza
2 answers
Answer question

0

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

about 4 years ago · Juan Pablo Isaza Report

0

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.

about 4 years ago · Juan Pablo Isaza Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!