This tutorial is part of our Learn React Guide

Submit an HTML Form in React

ByChris Sevon Jul 16, 2021

Sometimes we need to submit an HTML form embedded in a React component. We can use React's useRef() to submit a form.

This article isn't about any React form packages or validation. This article is about when you have a normal form that you need to submit from within a React function.

This is especially helpful for event tracking or doing some JavaScript stuff before you want the form to send a user away. We will use useRef() to keep a reference of the form and programmatically submit() it.

javascriptfunction Newsletter() {
  const formRef = useRef();

  function handleSubmit(e) {
    // stop the form from submitting automatically
    e.preventDefault();

    // do all the event tracking
    // or whatever you need

    // submit the form
    formRef.current.submit();
  }

  return (
    <form 
      ref={formRef} 
      onSubmit={handleSubmit} 
      method="POST" 
      action="https://formprocessing.com">

        {/* form inputs go here */}

    </form>
  )
}
Chris Sev

Chris Sev

Chris Sev is the co-founder of Better Dev. Coding better every day. Previously he created Scotch.io which was acquired.

Comments

What did you think of the article? Let us know!
(these comments are powered by GitHub issues and use 0 trackers)