I have a controlled form. If you type in the textarea and click the submit button it works. However im trying to also make the form submit when you press enter while typing. The following instead of submitting the form reload the page.
import React from 'react';
class PostComment extends React.Component {
constructor(props) {
super(props);
this.state = { value: '' };
this.handleChange = this.handleChange.bind(this);
this.handleSubmit = this.handleSubmit.bind(this);
this.keyDown = this.keyDown.bind(this);
}
handleChange(e) {
e.preventDefault();
this.setState({ value: e.target.value });
}
keyDown(e) {
if (e.keyCode == 13 && e.shiftKey == false) {
e.preventDefault();
this.myFormRef.submit();
}
}
handleSubmit(e) {
e.preventDefault();
const text = e.target.body.value;
// Call backend here
e.target.body.value = '';
}
render() {
return (
<form onSubmit={this.handleSubmit} ref={el => (this.myFormRef = el)}>
<textarea
rows="3"
name="body"
onKeyDown={this.keyDown}
value={this.state.value}
onChange={this.handleChange}
/>
<button className="btn" type="submit">
Comment
</button>
</form>
);
}
}
export default PostComment;