简体   繁体   中英

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:

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.

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM