reactjsreactjs-flux

How to submit a form using Enter key in react.js?


Here is my form and the onClick method. I would like to execute this method when the Enter button of keyboard is pressed. How ?

N.B: No jquery is appreciated.

comment: function (e) {
  e.preventDefault();
  this.props.comment({
    comment: this.refs.text.getDOMNode().value,
    userPostId:this.refs.userPostId.getDOMNode().value,
  })
},


<form className="commentForm">
  <textarea rows="2" cols="110" placeholder="****Comment Here****" ref="text"  /><br />
  <input type="text" placeholder="userPostId" ref="userPostId" /> <br />
  <button type="button" className="btn btn-success" onClick={this.comment}>Comment</button>
</form>

Solution

  • Change <button type="button" to <button type="submit". Remove the onClick. Instead do <form className="commentForm" onSubmit={onFormSubmit}>. This should catch clicking the button and pressing the return key.

    const onFormSubmit = e => {
      e.preventDefault();
      // send state to server with e.g. `window.fetch`
    }
    
    ...
    
    <form onSubmit={onFormSubmit}>
      ...
      <button type="submit">Submit</button>
    </form>
    

    Full example without any silly form libraries:

    function LoginForm() {
      const [email, setEmail] = useState('')
      const [password, setPassword] = useState('')
      const [submitting, setSubmitting] = useState(false)
      const [formError, setFormError] = useState('')
    
      const onFormSubmit = async (e: React.FormEvent<HTMLFormElement>) => {
        try {
          e.preventDefault();
          setFormError('')
          setSubmitting(true)
          await fetch(/*POST email + password*/)
        } catch (err: any) {
          console.error(err)
          setFormError(err.toString())
        } finally {
          setSubmitting(false)
        }
      }
    
      return (
        <form onSubmit={onFormSubmit}>
          <input type="email" autoComplete="email" value={email} onChange={e => setEmail(e.currentTarget.value)} required />
          <input type="password" autoComplete="current-password" value={password} onChange={e => setPassword(e.currentTarget.value)} required />
          {Boolean(formError) &&
            <div className="form-error">{formError}</div>
          }
          <button type="submit" disabled={submitting}>Login</button>
        </form>
      )
    }
    

    P.S. Remember that any buttons in your form which should not submit the form should explicitly have type="button".