Kinda Code
Home/React/React + TypeScript: Handling form onSubmit event

React + TypeScript: Handling form onSubmit event

Last updated: September 06, 2023

The example below shows you how to handle the form onSubmit event in React with TypeScript. We will use the new things, including functional components and hooks, and not use old stuff like class-based components.

Example Preview

Our sample project is really simple. It has a form with an input and a button. Once a user types in something and clicks on the button, we’ll alert the entered term. You can do other things like sending a request to an API as well.

Note that in order to prevent the page from reloading on the form onSubmit event, we need to call:

event.preventDefault();

What is the type of event? It is as follows:

event: React.FormEvent<HTMLFormElement>

For more clarity, see the complete code in the next section of this article.

The Steps

1. Create a new React project with this command:

npx create-react-app react_ts_form --template typescript

You can replace react_ts_form with whatever name you want.

2. Remove all of the default code in your src/App.tsx and add the following:

// Kindacode.com
// App.tsx
import React, { useState } from 'react';

import './App.css';

const App = () => {
  const [term, setTerm] = useState('');

  const submitForm = (event: React.FormEvent<HTMLFormElement>) => {
    // Preventing the page from reloading
    event.preventDefault();

    // Do something 
    alert(term);
  }

  return (
    <div className="container">
      <form onSubmit={submitForm}>
        <input
          value={term}
          onChange={(e) => setTerm(e.target.value)}
          type="text"
          placeholder="Enter a term"
          className="input"
        />
        <button type="submit" className="btn">Submit</button>
      </form>
    </div>
  );
};

export default App;

3. And replace the unwanted CSS code in your src/App.css with this:

/* App.css */
.container {
  margin: auto;
  padding-top: 30px;
  width: 330px;
}

.input {
  margin-bottom: 30px;
  padding: 5px 15px;
  width: 300px;
}

.btn {
  padding: 5px 10px;
  cursor: pointer;
}

4. Run the project:

npm start

Go to http://localhost:3000 and see your work.

Conclusion

You’ve learned how to handle the onSubmit event in React and TypeScript.

Using TypeScript with React makes you write more code, but in return, it also gives you a lot of benefits, especially in large projects that need long-term development and maintenance with teams with lots of people involved. If you would like to explore more things about modern React, take a look at the following articles:

You can also check our React topic page and React Native topic page for the latest tutorials and examples.

Related Articles