Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to select form element with React JS?

Tags:

reactjs

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 with React?

For some context, I am trying to write an editable form element that the user can edit by clicking it, similar to the code in this gist: https://gist.github.com/hanneshapke/4a12dd414a193d5406ea. However, this gist does not automatically select the form field when it goes into edit mode, and the user has to click again to change the text.

like image 994
Ceasar Bautista Avatar asked Jul 22 '26 09:07

Ceasar Bautista


1 Answers

Don't operate DOM directly!

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

render() {   
    return (
        <div>              
            <input ref="myFoo" type="text" value="123"/>
        </div>             
    );                     
}
like image 191
TonyY Avatar answered Jul 23 '26 22:07

TonyY



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!