Home > Blockchain >  Dynamically change font-size to fit text into container
Dynamically change font-size to fit text into container

Time:11-24

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:

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.

CodePudding user response:

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 }} ...

  • Related