/react-managed-input

Primary LanguageJavaScriptMIT LicenseMIT

npm version

react-managed-input

Motivation

Have you ever needed to write managed input modifying value on the fly? Like this one:

class TrimmingInput extends React.Component {
  state = { value: '' };

  handleChange = (event) => {
    const value = event.target.value;
    const trimmedValue = value.replace(/\s+/g, ' ').trimLeft();
    this.setState({ value: trimmedValue });
  };

  render() {
    return <input value={this.state.value} onChange={this.handleChange} />
  }
}

You probably encountered problems with caret jumping at the end of the input whenever you try to input value that will be trimmed. So this component will allow you to manage caret position and handle properly this kinds of problems.

Check the example to see what I'm writing about (source code).

Browser compatibility

This component uses Selection API check if you can use it. (click here)

Prop Types

onChange

(value: string, selection: Selection, prevSelection: Selection, event: object): void

Callback invoked whenever value of the input is changed. Selection is object of type: { start: number, end: number, direction: string }.

innerRef

(node: Node):void

Callback invoked at mount time allows assigning inner component.

Public Methods

setSelectionRange

(start: number, end: number, direction: string = 'forward'): void

Will set selection after next render. When end argument is not provided then is set to the same value as start.