reactjsinputonchange

Scale text on change relative to container in React


I'm using React.js and I want input text to fit it's container but onChange.

For example: if a user enter 'T'

enter image description here

and then he enters 'E', so the input now is 'TE'

enter image description here


Solution

  • I have created one small application demoing this. I am using a couple of state text which manages the current text in a textbox and a fontSize which is used to calculate the current font size for text. I have kept an upper size of 200px and a lower size of 50px so, that text doesn't look too large or small. The ratio is 1.2 which means whenever some add a new character text size will increase to 1.2 and if a character is removed then the size would reduce by 1.2. Here is an application.

    import React, { useState, useCallback } from "react";
    
    export default function App() {
      const [fontSize, setFontSize] = useState(200);
      const [text, setText] = useState("");
      const updateFontSize = useCallback(
        (value) => {
          if (text.length > value.length) {
            const textSize = Math.ceil(fontSize * 1.5, 10);
            fontSize < 200 && setFontSize(textSize);
          } else if (text.length < value.length) {
            const textSize = Math.ceil(fontSize / 1.5, 10);
            fontSize > 50 && setFontSize(textSize);
          }
          setText(value);
        },
        [fontSize, text]
      );
      return (
        <div className="App">
          <input
            type="text"
            onChange={(event) => updateFontSize(event.target.value)}
          />
          <div style={{ fontSize: `${fontSize}px` }}>{text}</div>
        </div>
      );
    }
    

    Here is a code sandbox link for your reference.