Problem:
is there a way to change the style of input width as we type in React?
My initial width
of my input is 1ch
. I want to make it increase/decrease when the character growing/shrinking while I’m typing/focus, so the % will stay at the end.
my code onChanges for the style is this line
e.target.style.width = e.target.value.length + 'ch'
But seems didn’t work at all. How to trigger this input size width?
Solution:
You can change the style of input width as we type in React like this example component
import React, { useState } from 'react';
const InputComponent = () => {
const [inputValue, setInputValue] = useState('');
const handleChange = (e) => {
setInputValue(e.target.value);
};
return (
<div>
<input
type="text"
value={inputValue}
onChange={handleChange}
style={{ width: `${inputValue.length}ch` }}
/>
</div>
);
};
export default InputComponent;