Repository URL to install this package:
|
Version:
8.0.0 ▾
|
import React, { Component } from 'react';
import TextAreaAutosize from 'react-textarea-autosize';
import PropTypes from 'prop-types';
import classNames from 'classnames';
import noop from 'lodash/noop';
class Textarea extends Component {
static propTypes = {
value: PropTypes.string,
className: PropTypes.string,
onChange: PropTypes.func,
placeholder: PropTypes.string,
onBlur: PropTypes.func,
minRows: PropTypes.number,
maxRows: PropTypes.number,
disabled: PropTypes.bool,
onKeyDown: PropTypes.func,
textAreaRef: PropTypes.func,
maxLength: PropTypes.number,
wrap: PropTypes.string,
style: PropTypes.object,
autoFocus: PropTypes.bool,
};
static defaultProps = {
value: '',
className: '',
onChange: noop,
placeholder: '',
onBlur: noop,
onKeyDown: noop,
minRows: 1,
maxRows: 1,
disabled: false,
textAreaRef: noop,
maxLength: 1000,
wrap: 'soft',
style: null,
autoFocus: false,
};
constructor(props) {
super(props);
this.state = {
currentValue: props.value,
initialValue: props.value,
};
}
static getDerivedStateFromProps(newProps, prevState) {
if (prevState.initialValue !== newProps.value) {
return { ...prevState, currentValue: newProps.value, initialValue: newProps.value };
}
return null;
}
/**
* Textarea inputs place cursor at beginning of value, so by overriding the target value
* with an empty string and setting it to the stored value this will focus the cursor to the end.
*/
onFocus = e => {
const existingValue = e.target.value;
e.target.value = '';
e.target.value = existingValue;
};
handleChange = e => {
const { onChange } = this.props;
this.setState({ currentValue: e.target.value });
onChange(e);
};
render() {
const {
placeholder,
onBlur,
disabled,
minRows,
maxRows,
className,
onKeyDown,
textAreaRef,
maxLength,
wrap,
style,
autoFocus,
} = this.props;
const { currentValue } = this.state;
return (
<TextAreaAutosize
inputRef={textAreaRef}
className={classNames(className, 'Input-field')}
value={currentValue}
onChange={this.handleChange}
onKeyDown={onKeyDown}
placeholder={placeholder}
onBlur={onBlur}
disabled={disabled}
minRows={minRows}
maxRows={maxRows}
maxLength={maxLength}
wrap={wrap}
style={style}
autoFocus={autoFocus}
onFocus={this.onFocus}
/>
);
}
}
export default Textarea;