Reaction prevents form submission when entering input inside input

Reaction prevents form submission when a button is clicked

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

<SearchBar onInputChange={this.handleInputChange} /> 

Each time the user changes the input, the parent container will be notified. That's why there is no submit button in my search bar.

However, I find that if I press the enter button inside my search bar, the whole page refreshes. And I do not want this.

I know that if I have a button in the form, I can call event.preventDefault (). But in this case I donโ€™t have a button, so I donโ€™t 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 
+15
source share
3 answers

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

The simplest implementation:

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

But ideally, you create a dedicated handler for this:

 <form onSubmit={this.submitHandler}> 

with the next implementation

 submitHandler(e) { e.preventDefault(); } 
+21
source

I'm not sure if this works for every situation, because when you press enter in the form input field, you will still call the onSubmit method, although the default submission will not happen. This means that you will still run the pseudo-submit action designed for your form. One liner with ES6 that solves the problem specifically and completely:

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

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

+2
source

In a React component with a Search input field nested in a larger (not React OR React) form, this worked best for me in all 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 answer) is incorrect: you do not need event.target. This is an input field. You want the event itself. And in React (in particular, at the moment 16.8) you need event.key (e.key, whatever you want it to be called).

0
source

All Articles