Growing Input
by cabralpinto
HTML
<div id="app"></div>
CSS
wrapper > * {
font-family: "Times New Roman", Times, serif;
font-size: 1em;
}
#hide {
position: absolute;
opacity: 0;
z-index: -100;
white-space: pre;
}
input {
min-width: 1px;
padding: 0;
}
React
const { useState, useRef, useEffect } = React;
const Input = () => {
const [content, setContent] = useState('');
const [width, setWidth] = useState(0);
const span = useRef();
useEffect(() => {
setWidth(span.current.offsetWidth);
}, [content]);
const changeHandler = evt => {
setContent(evt.target.value);
};
return (
<wrapper is="custom">
<span id="hide" ref={span}>{content}</span>
<input type="text" style={{ width }} autoFocus onChange={changeHandler} />
</wrapper>
);
};
const App = () => <p>Lorem ipsum <Input /> egestas arcu.</p>;
ReactDOM.render(<App />, document.querySelector("#app"))