Skip to content

Cannot declaratively specificy select position for controlled input elements #5951

Closed
@dminkovsky

Description

@dminkovsky

I am working on a component that has a controlled input element. The component has an onChange handler that manipulates user input before setting the value back on the input's value prop. As a result of this manipulation, the caret position as restored by React may be different than where the user was typing.

To control this situation, I keep track of the caret position in the component's state:

onKeyUp({ target }) {                    // also in `onChange`, `onMouseUp`, etc
    this.saveSelectState(target);
}

and then set it back to the desired position after the component updates:

componentDidUpdate() {
    const { selectionStart, selectionEnd } = this.state;
    const { input } = this.refs;

    try {        
        if (input === document.activeElement) {
            input.setSelectionRange(selectionStart, selectionEnd);
        }
    } catch(e) {}
}

The API I desire, however, would be more like:

<input
    type='text'
    selectionStart={ 5 }
    selectionEnd={ 5 }
    ... and so on
/>

It was pretty simple to implement this abstraction for myself, but it seems like something that's actually missing from React. I think this goes along well with the idea that React is an API for declaratively controlling UI components' state.

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions