Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Dynamically change font-size to fit text into container

I created a react componentn whicht displays a label for an input filed. Since the label text is of variable length I am trying to dynamically change the font size in order for the text to fit into the fix sized container.

However, somehow my font-size does not get updated when the function gets called and I can not figure out why.

Here is my code:

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

import React from "react";
class NewDrive extends React.Component {
  constructor(props) {
    super(props);

    this.myOutputRef = React.createRef();
    this.myOutputContainerRef = React.createRef();

    this.size = 50 + "px";
  }

  componentDidMount() {
    const output = this.myOutputRef.current;
    const outputContainer = this.myOutputContainerRef.current;
    this.size = parseFloat(this.size) - 40 + "px";

    if (output.clientHeight >= outputContainer.clientHeight) {
      this.componentDidMount();
    }
  }

  render() {
    return (
      <form onSubmit={this.handleSubmit}>
        <div className="input-wrapper">
          <label ref={this.myOutputContainerRef}>
            <div style={{ fontSize: this.size }} ref={this.myOutputRef}>
              Gas cost
            </div>
          </label>
          <input
            type="text"
            value={this.state.from}
            onChange={this.handleChange}
          />
        </div>
      </form>
    );
  }
}

export default NewDrive;

I have also tried to update the fontzize with a call like output.style.fonSize = ... but this did not work either.

>Solution :

Variable this.size is not part of a state of component.

Try editing the constructor

constructor(props) {
    super(props);
    this.state = {
        size: 50 + "px",
    }

    this.myOutputRef = React.createRef();
    this.myOutputContainerRef = React.createRef();
  }

then update the size variable by this.setState({size: parseFloat(this.size) - 40 + "px"}), and lastly, change in the render method how you access the size variable – ... style={{ fontSize: this.state.size }} ...

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading