I came across with this scenario where I want to "sanitize" the input before calling onChange, however even without re-render, the cursor moves to the end. why?
class Input extends React.Component {
state = { value: this.props.value };
onChange = e => {
let nextValue = e.target.value;
if (!/[0-9]/.test(nextValue)) {
this.setState({ value: nextValue });
}
};
render() {
console.log("render");
return (
<input type="text" value={this.state.value} onChange={this.onChange} />
);
}
}
ReactDOM.render(<Input value="type something here" />, 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"/>