Empresas
Empleos
  • Sobre nosotros
  • Soluciones
    • Publicación de vacantes
      Publica tu vacante y recibe candidatos calificados en 48h.
    • Evaluación de candidatos
      500+ pruebas técnicas y psicológicas, más anti-fraude.
    • Headhunting
      Búsqueda ejecutiva a la medida de principio a fin.
    • Nómina + EOR
      Dispersión de nómina y EOR en más de 15 países de LATAM.
  • Precios
  • Empleos

0

97
Vistas
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.

about 4 years ago · Juan Pablo Isaza
1 Respuestas
Responde la pregunta

0

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

about 4 years ago · Juan Pablo Isaza Denunciar
Responde la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Comercial
Legal
Términos y condiciones Política de privacidad
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomiéndame algunas ofertas
Necesito ayuda