What I'm trying to achieve is a textarea that auto resizes when user continues to type or pastes a long text into text area.
This is what I have.
class TextArea extends InputBase {
render() {
const { label, placeholder, wrap, rows, cols, disabled, style, textStyle, textClass, value } = this.props;
return (
<div className={formClass} style={style}>
{!!label && (<label className="control-label" htmlFor={this.id}>{label}</label>)}
<textarea id={this.id} className={`form-control ${textClass}`} placeholder={placeholder} disabled={disabled} style={textStyle}
rows={rows} cols={cols} wrap={wrap} value={this.state.value || ''}
onChange={this.onChange} onBlur={this.onBlur} onFocus={this.onFocus} onKeyPress={this.onKeyPresses} onKeyUp={this.onKeyUp}>{value}</textarea>
</div>
);
}
}
Any suggestion for how I might be able to resize the textarea so it will expand according to the length of content in textarea.
You can solve this mostly with CSS using an approach that's outlined in css-tricks.com.
The solution is to put your textarea inside a div, make your div match the styling of the textarea, then use display:grid to make the textarea expand to fill its parent container as it grows:
.grow-wrap {
/* easy way to plop the elements on top of each other and have them both sized based on the tallest one's height */
display: grid;
}
.grow-wrap::after {
/* Note the weird space! Needed to preventy jumpy behavior */
content: attr(data-replicated-value) " ";
/* This is how textarea text behaves */
white-space: pre-wrap;
/* Hidden from view, clicks, and screen readers */
visibility: hidden;
}
.grow-wrap>textarea {
/* You could leave this, but after a user resizes, then it ruins the auto sizing */
resize: none;
/* Firefox shows scrollbar on growth, you can hide like this. */
overflow: hidden;
}
.grow-wrap>textarea,
.grow-wrap::after {
/* Identical styling required!! */
border: 1px solid black;
padding: 0.5rem;
font: inherit;
/* Place on top of each other */
grid-area: 1 / 1 / 2 / 2;
}
<div class="grow-wrap">
<textarea name="text" id="text" onInput="this.parentNode.dataset.replicatedValue = this.value"></textarea>
</div>