Monday, June 3, 2024
 Popular · Latest · Hot · Upcoming
66
rated 0 times [  68] [ 2]  / answers: 1 / hits: 89362  / 7 Years ago, wed, may 3, 2017, 12:00:00

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

More From » reactjs

 Answers
5

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

[#57920] Monday, May 1, 2017, 7 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
denism

Total Points: 627
Total Questions: 96
Total Answers: 98

Location: Ivory Coast
Member since Sun, Mar 7, 2021
3 Years ago
;