1

I am having a input in react component, When the input is inside , Enter button will trigger a click, but if input is not wrapped inside form, Enter does not work,

Is wrapping input by form the only way to activate Enter button ?

    <div>
        <input name=“name” type="text"
           value={somevalue} onChange={this.handleChange}/>
        <button  id=“searchbutton”
            onClick={this.handleSubmit}>
            {search label}
        </button>
    </div>
Ilona
  • 101
  • 9
Parameswar
  • 1,951
  • 9
  • 34
  • 57

2 Answers2

2

Is wrapping input by form the only way to activate Enter button ?

Your other option is to use a keypress handler on the input and check for the Enter key.

The reason it works when this is in a form is that browsers automatically click the submit button on a form if the form has only a single text input and the user presses Enter. Without the form, you don't get that automatic behavior.

T.J. Crowder
  • 1,031,962
  • 187
  • 1,923
  • 1,875
  • This is exactly what I had to do with an `input` that I had created outside of a form. I had to create a separate `keypress` handler for it to handle the user pressing the enter key. This, for me, is the best solution to this if for some reason you don't want to use a form. – AJC24 Jul 31 '19 at 07:22
  • @OsamaKhalid - Right, which is why the OP sees the behavior he sees when this is in a `form`. I'm not sure why the comment...? – T.J. Crowder Jul 31 '19 at 07:24
0
//By default in form type of button is "submit". Change that to : 
    <button  type="button" id="searchbutton"
           onClick={this.handleSubmit}>
           {search label}
    </button>
Osama Khalid
  • 307
  • 4
  • 14