React prevent form submission when enter is pressed inside input

JavascriptReactjs

Javascript Problem Overview


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

Javascript Solutions


Solution 1 - Javascript

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();
}

Solution 2 - Javascript

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).

Solution 3 - Javascript

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.

Solution 4 - Javascript

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(); }}

Solution 5 - Javascript

prevent for Enter key for search input:

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

Solution 6 - Javascript

This works for me:

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

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionErnieKevView Question on Stackoverflow
Solution 1 - JavascriptzerkmsView Answer on Stackoverflow
Solution 2 - JavascripteonView Answer on Stackoverflow
Solution 3 - JavascriptDavid KamerView Answer on Stackoverflow
Solution 4 - JavascriptMatteo GalliView Answer on Stackoverflow
Solution 5 - JavascriptMahdi AfzalView Answer on Stackoverflow
Solution 6 - JavascriptStanislau LadutskaView Answer on Stackoverflow