Reputation: 369
I have a textarea with auto increment row. And i want to set auto decrement when i delete my text . How can i do it?
Here is my code:
<textarea name="content" rows={this.state.rows} className="text-area"
placeholder="Content" onInput={this.autoHeight} onChange={this.onChange} value={this.state.content}/>
autoHeight = (elem) => {
if (elem.target.scrollHeight > this.state.rows * 15) {
this.setState({ rows: this.state.rows + 1 });
}
}
this.state = {
rows: 6,
content: ''
}
Upvotes: 1
Views: 204
Reputation: 29282
instead of setting rows
attribute on the textarea
and using autoHeight
to increase the height of the textarea
, set min-height
on the textarea
and use onChange
event handler to increase or decrease the height of the textarea
class App extends React.Component {
constructor() {
super();
this.state = {
content: '',
minHeight: 100
}
}
onChange = ({ target }) => {
const paddingTop = parseInt(getComputedStyle(target).getPropertyValue('padding-top'));
const paddingBottom = parseInt(getComputedStyle(target).getPropertyValue('padding-bottom'));
const verticalPadding = paddingTop + paddingBottom;
target.style.height = 0;
target.style.height = Math.max(target.scrollHeight - verticalPadding, this.state.minHeight) + 'px';
this.setState({ content: target.value });
}
render() {
return (
<div>
<textarea
name="content"
placeholder="Content"
onChange={this.onChange}
value={this.state.content}
style={{ minHeight: this.state.minHeight, padding: '10px' }}
/>
</div>
);
}
}
ReactDOM.render(<App />, document.getElementById('root'));
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/16.6.3/umd/react.production.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react-dom/16.6.3/umd/react-dom.production.min.js"></script>
<div id="root"></div>
Upvotes: 3