I am creating a “wrapper” class component for the <input>
element, whose aim is to prevent the insertion of some characters.
The problem is that, when I initialize its state in the constructor, I get the ESLint error react/no-direct-mutation-state
. I know I could simply ignore it by disabling the ESLint rule for that line, but I would like to understand whether the problem I am experiencing is a “bug” in the plugin, as it seems to me (documentation here: https://github.com/yannickcr/eslint-plugin-react/blob/master/docs/rules/no-direct-mutation-state.md), or whether I am doing something wrong.
Here it is the component code:
import React from 'react';
const FORBIDDEN_CHARS = '[@&*%?(){}[]|^!:;\/~+"`=$]';
class SecuredInput extends React.Component {
constructor(props) {
super(props);
this.inputRef = React.createRef();
this.state = { // <-- this is the line generating the error
value: ''
};
this.handleInput = this.handleInput.bind(this);
}
componentDidMount() {
if (this.props.value) {
this.setState({
value: this.props.value
});
}
}
handleInput(str) {
const re = this.props.type === 'number'
? new RegExp('[^0-9]', 'g')
: new RegExp(this.props.forbiddenChars, 'gi');
this.setState({
value: str.replace(re, '');
});
}
render() {
return (
<input
{...this.props}
ref={this.inputRef}
value={this.state.value}
onInput={(event) => this.handleInput(event.target.value)}
/>
);
}
}
SecuredInput.defaultProps = {
forbiddenChars: FORBIDDEN_CHARS
};
export default SecuredInput;