1

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;
Evanss
  • 23,390
  • 94
  • 282
  • 505

1 Answers1

0

My first guess would be that *.submit() does not trigger the onSubmit event, see also a similar question here, which suggests calling the onsubmit handler directly (in this case this would mean e.g. calling this.handleSubmit with a "fake" event payload) ... Another way you could work around this problem would be to trigger the submit button click rather than the form submit on enter:

 keyDown () {
   if (e.keyCode == 13 && e.shiftKey == false) {
     e.preventDefault();
     this.button.click();
   }
 }

 render() {
   return (
     <form onSubmit={this.handleSubmit}>
      <textarea
        rows="3"
        name="body"
        onKeyDown={this.keyDown}
        value={this.state.value}
        onChange={this.handleChange}
      />
      <button className="btn" type="submit" ref={el => (this.button = el)}>
        Comment
      </button>
    </form>
  );
}