How do I select a form element using React JS?

How can I write a React component that will automatically select a form field?

For example, in jQuery, you can automatically select a form field using select () :

<html lang="en">
<head>
  <meta charset="utf-8">
  <title>select demo</title>
  <script src="https://code.jquery.com/jquery-1.10.2.js"></script>
</head>
<body>
  <input type="text" name="foo" value="Some text">
<script>
  $("input").select();
</script>
</body>
</html>

      

How can I achieve a similar effect using React?

In some context, I'm trying to write an editable form element that the user can edit by clicking it, similar to the code in this value: https://gist.github.com/hanneshapke/4a12dd414a193d5406ea . However, this option does not automatically select the form field when it enters edit mode and the user must click again to change the text.

+3


source to share


2 answers


Don't use the DOM directly!



componentDidMount() {      
    this.refs.myFoo.select();       
} 

render() {   
    return (
        <div>              
            <input ref="myFoo" type="text" value="123"/>
        </div>             
    );                     
}

      

+2


source


To answer your question in the context of the code snippet you linked to, I would use a combination of refs and setSelectionRange:



handleEdit (e) {
    this.textInput.setSelectionRange(0, this.textInput.value.length)
    return (e) => this.setState({
      editing: !this.state.editing
    });
  }

render() {
   //...

   // setting the ref on render...
   <input
      type="text"
      ref={(input) => { this.textInput = input; }}
      //...
   />
}

      

0


source







All Articles