Cursor reset issue 2

Simple example of cursor position reseting even with state managment.

by Christian Micle

HTML

<script src="https://unpkg.com/react@16/umd/react.development.js"></script>
<script src="https://unpkg.com/react-dom@16/umd/react-dom.development.js"></script>
<div id="container">
    <!-- This element's contents will be replaced with your component. -->
</div>

Babel + JSX

function getValue(value) {
	return value != null
		? value
		: '';
}

class TestInput extends React.Component {
  constructor(props) {
    super(props);

    this.handleChange = this.handleChange.bind(this);
    
    this.state = { value: '' };
  }
  
  static getDerivedStateFromProps(nextProps) {
  	return {
			value: getValue(nextProps.value),
		};
  }
  
  shouldComponentUpdate(nextProps, nextState) {
	  return nextState.value != this.state.value;
  }

  handleChange(event) {
    const {
      onChange,
    } = this.props;
    
    this.setState({
      value: event.target.value,
    });

    onChange(event.target.value);
  }

  render() {
    const { value } = this.state;

    return <input value={value} onChange={this.handleChange} />
    ;
  }
}

class TestParent extends React.Component {
  constructor(props) {
    super(props);

		this.handleChange = this.handleChange.bind(this);

    this.state = {
      value: null,
    };
  }

  handleChange(value) {      
    setTimeout(() => {
      this.setState({
 				value,
      });
    }, 1);
  }

  render() {
    const {
      value
    } = this.state;

    return <TestInput value={value} onChange={this.handleChange}/>;
  }
}

ReactDOM.render(
  <TestParent />,
  document.getElementById('container')
);