Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to keep cursor position in a react input element

The cursor keeps going to the end. How to keep the cursor position when editing from the the middle of the string?

enter image description here

Code that I am using is:

const rootElement = document.getElementById('root');

class MyFancyForm extends React.Component {

    constructor(props) {
        super(props);
        this.state = {myValue: ""};
    }

    handleCommaSeparatedChange = event => {
        const {value} = event.target;
        this.setState({myValue: value});
    };




    render() {
        return(
            <form >

                <div>
                    <label>
                        Cursor position looser
                        <br />
                        <input onChange={this.handleCommaSeparatedChange} value={this.state.myValue} />
                    </label>
                </div>


            </form>
        )
    }
}

const element = <MyFancyForm />;

ReactDOM.render(element, rootElement);

Any idea how could I achieve it?

like image 936
redochka Avatar asked Feb 18 '19 10:02

redochka


People also ask

How do I set the cursor position in input?

To move the cursor to the end of an input field: Use the setSelectionRange() method to set the current text selection position to the end of the input field. Call the focus() method on the input element. The focus method will move the cursor to the end of the input element's value.

How do I get my cursor position in Reactjs?

To get the mouse position in React: Set the onMouseMove prop on an element or add an event listener on the window object. Provide an event handler function. Access relevant properties on the event object.


1 Answers

just change value into defaultValue - it worked both in codepen and codesandbox for me

class MyFancyForm extends React.Component {

    constructor(props) {
        super(props);
        this.state = {myValue: ""};
    }

    handleCommaSeparatedChange = event => {
        const {value} = event.target;
        this.setState({myValue: value});
    };




    render() {
        return(
            <form >

                <div>
                    <label>
                        Cursor position looser
                        <br />
                        <input onChange={this.handleCommaSeparatedChange} defaultValue={this.state.myValue} />
                    </label>
                </div>


            </form>
        )
    }
}


  ReactDOM.render(
    <MyFancyForm />,
    document.getElementById('root')
  );

like image 165
Waseem Raja Shaik Avatar answered Sep 19 '22 13:09

Waseem Raja Shaik