79

React prevent form submission when enter is pressed

I have the following React Search Bar component where the parent container can call using

<SearchBar onInputChange={this.handleInputChange} />

Everytime the user changes the input, the parent container will be notified. This is why my search bar does not need any submit button.

However, I am finding that if I press enter inside my search bar, the whole page refreshes. And I dont want that.

I know if I have a button in the form, I could call event.preventDefault(). But in this case I have no button so I dont know what to do here

class SearchBar extends Component {
    constructor(props) {
        super(props);
        this.state = { value: '' };
        this.handleChange = this.handleChange.bind(this)
    }

    handleChange(e) {
        this.setState({ value: e.target.value });
        this.props.onInputChange(e.target.value);
    }

    render() {
        return (
        <div id="search-bar">
            <form>
            <FormGroup controlId="formBasicText">
                <FormControl
                type="text"
                onChange={this.handleChange}
                value={this.state.value}
                placeholder="Enter Character Name"
                />          
            </FormGroup>
            </form>
        </div>
        );
    }
}

export default SearchBar
3
  • 2
    Is there a reason you need to use a form tag? If you replace that with a div then enter won't submit. Commented May 3, 2017 at 3:03
  • Div would word too. I had a form there just incase I want to add more fields in the future and form allows more control Commented May 3, 2017 at 5:11
  • That is bad practice. You use form where it makes sense semantically, not because of the added enter functionality. Commented May 10, 2024 at 23:51

7 Answers 7

108

You need to create a form handler that would prevent the default form action.

The simplest implementation would be:

<form onSubmit={e => { e.preventDefault(); }}>

But ideally you create a dedicated handler for that:

<form onSubmit={this.submitHandler}>

with the following implementation

submitHandler(e) {
    e.preventDefault();
}
Sign up to request clarification or add additional context in comments.

4 Comments

Is the second form more ideal for readability mostly? Or are there other reasons?
@TroyCosentino other reasons: in the first e => { e.preventDefault(); } this is an anonymous function which is recreated every render loop, so react replaces it in the child element. With a dedicated handler a function instance only created once and then left untouched.
Didn't work for me. What did work is ` onKeyPress={(e) => { e.key === 'Enter' && e.preventDefault(); }}` on <form>.
@AviKaminetzky it's impossible e.key === 'Enter' condition could change anything in the behaviour. It's likely that you have some other problem there. Also I don't see how onKeyPress makes any sense for a form.
48

In a React component with a Search input field, nested in a larger (non-React OR React) form, this worked best for me across browsers:

<MyInputWidget
  label="Find"
  placeholder="Search..."
  onChange={this.search}
  onKeyPress={(e) => { e.key === 'Enter' && e.preventDefault(); }}
  value={this.state.searchText} />

(e)=>{e.target.keyCode === 13} (@DavidKamer's answer) is incorrect: You don't want the event.target. That's the input field. You want the event itself. And in React (specifically 16.8, at the moment), you want event.key (e.key, whatever you want to call it).

3 Comments

The React events list for keyboard events in v 17.0.1 are: onKeyDown onKeyPress onKeyUp See reactjs.org/docs/events.html#keyboard-events I don't know whether these are polyfilled to what's not deprecated. Haven't looked into that. But onKeyDown or onKeyUp should work fine for most usages, in my example above. --thanks
The answer by @zerkms did not work for me either but this solution works. I've updated the prop from onKeyPress to onKeyDown since onKeyPress is deprecated.
13

I'm not sure if this works for every situation, as when you press enter in a form's input field you will still trigger the onSubmit method, although the default submit won't occur. This means that you will still trigger your pseudo submit action that you've designed for your form. A one liner with ES6 that solves the problem specifically and entirely:

<input onKeyPress={(e)=>{e.target.keyCode === 13 && e.preventDefault();}} />

This solution should have 0 side effects and solves the problem directly.

6 Comments

This is a good solution if there's only 1 input, handling it at the onSubmit level is better for a form with multiple controls
My solution works in many situations that would land someone here. Many people will try the above solution only to find that it prevents the enter key for every part of a form. More specific is better in situations where you want other functionality to continue as it would by default. If you have a single input or component in a form that you don't want to trigger your submit function for, this is the only solution that will work. Other methods will explicitly disable the enter button or will explicitly disable submitting with html5 standards, but will not do what is asked.
Thank you. Disabling submit for a single input out of several is exactly what I was looking to do.
For me e.target.keyCode turned up undefined, but e.key === 'Enter' works great.
|
13

The best way to prevent the ENTER, as suggested also by Eon is to add the following to your input element:

onKeyPress={(e) => { e.key === 'Enter' && e.preventDefault(); }}

1 Comment

9

This works for me:

<Input
   ...
   onKeyDown={(e) => { e.key === 'Enter' && e.preventDefault() }}
/>

Comments

3

This works for me:

<form ...>
    {/* Prevent implicit submission of the form */}
    <button
        aria-hidden="true"
        className="hidden"
        disabled
        type="submit"
     ></button>

For those interested in the literature

TL;DR:

4.10.22.2 Implicit submission
A form element's default button is the first submit button in tree order whose form owner is that form element.

If the user agent supports letting the user submit a form implicitly (for example, on some platforms hitting the "enter" key while a text field is focused implicitly submits the form), then doing so for a form whose default button has a defined activation behavior must cause the user agent to run synthetic click activation steps on that default button.

Consequently, if the default button is disabled, the form is not submitted when such an implicit submission mechanism is used. (A button has no activation behavior when disabled.)

1 Comment

I think this is the superior answer in 2022 – it allows the "enter" keydown to function as form submit once the conditions for submit are met. Way less boilerplate vs. a conditional e.preventDefault() for every input field.
0

prevent for Enter key for search input:

<input type="text" onKeyDown={e => {
  if (e.key === 'Enter') e.preventDefault();
}} />

1 Comment

onKeyPress is deprecated, use onKeyDown instead.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.