ANOTHER SIMPLE APPROACH (without additional package)
export class foo extends React.Component { handleKeyDown(e) { e.target.style.height = 'inherit'; e.target.style.height = '${e.target.scrollHeight}px';
The problem when you delete text and the text area is not compressed is that you forgot to set this line
e.target.style.height = 'inherit';
Try using onKeyDown because it works for all keys while others cannot ( w3schools )
In case you have padding or border top or bottom . ( link )
handleKeyDown(e) { // Reset field height e.target.style.height = 'inherit'; // Get the computed styles for the element const computed = window.getComputedStyle(e.target); // Calculate the height const height = parseInt(computed.getPropertyValue('border-top-width'), 10) + parseInt(computed.getPropertyValue('padding-top'), 10) + e.target.scrollHeight + parseInt(computed.getPropertyValue('padding-bottom'), 10) + parseInt(computed.getPropertyValue('border-bottom-width'), 10); e.target.style.height = '${height}px'; }
I hope this can help.
source share