Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

insert at cursor in react

I need to insert text at caret (current cursor position) in the React-controlled textarea (like autocomplete).

For vanilla textarea I used this code:

insertAtCursor: function (myField, myValue) {
    // IE
    if (document.selection) {
        myField.focus();
        var sel = document.selection.createRange();
        sel.text = myValue;
    } 
    // FF
    else if (myField.selectionStart || myField.selectionStart == '0') {
        var startPos = myField.selectionStart;  var endPos = myField.selectionEnd;
        myField.value = myField.value.substring(0, startPos)
        + myValue + myField.value.substring(endPos, myField.value.length);
    } else {
        myField.value += myValue;
    }
}

but it does not work in React. How can I do it?

like image 801
wizzard0 Avatar asked Mar 14 '14 16:03

wizzard0


1 Answers

You need to get the node, by doing this.getDOMNode(). Depending on the rest of your code, you might need to find the textarea within that node; or refactor your textarea into its own component and use refs.

insertAtCursor: function (myField, myValue) {
    var myField = this.getDOMNode();

    // the rest of your code
}

A nicer alternative is to just determine the cursor position, and insert your new string; and store it back in your state. This is what I'd recommend.

var index = getCursorPosition();
this.setState({
  value: this.state.value.slice(0, index) + theNewString + this.state.value.slice(index + 1)
})
like image 199
Brigand Avatar answered Nov 15 '22 00:11

Brigand