Resize input depending on the text length in React

If you want to resize an input in React depending on the text length, you can use the style prop and set the width of the element in ch units (length of the first character).

Example:

jsx
import React, { useState } from 'react';

const ResizableInput = () => {

    const [text, setText] = useState('');

    return(
        <input 
            value    = {text} 
            onChange = {(e) => setText(e.target.value)} 
            style    = {{width: `${text.length}ch`}}
        />
    );

}

export default ResizableInput;

Hi, I'm Erik, an engineer from Barcelona. If you like the post or have any comments, say hi.