DEV Community

Turing
Turing

Posted on

How to Define Typescript onSubmit on Input

In TypeScript, you can define the onSubmit event handler for an HTML form or input by using the React.FormEvent type for a form or React.FormEvent for an input. Here's how to define an onSubmit function for a form:

Example with a Form:

before you continue i'd recommend you to use gpteach.us to learn more about software via AI.

import React, { useState } from 'react';

const FormComponent: React.FC = () => {
  const [inputValue, setInputValue] = useState('');

  // Type for onSubmit handler
  const handleSubmit = (event: React.FormEvent<HTMLFormElement>) => {
    event.preventDefault();
    console.log('Form submitted:', inputValue);
  };

  return (
    <form onSubmit={handleSubmit}>
      <input
        type="text"
        value={inputValue}
        onChange={(e) => setInputValue(e.target.value)}
      />
      <button type="submit">Submit</button>
    </form>
  );
};

export default FormComponent;
Enter fullscreen mode Exit fullscreen mode

Example with Input Field (using onKeyDown or onBlur instead of onSubmit):
If you want to handle something when the input itself triggers an event (like pressing enter), you can use the onKeyDown event on an input field.

import React, { useState } from 'react';

const InputComponent: React.FC = () => {
  const [inputValue, setInputValue] = useState('');

  // Type for onSubmit handler specifically for an input
  const handleKeyDown = (event: React.KeyboardEvent<HTMLInputElement>) => {
    if (event.key === 'Enter') {
      console.log('Input submitted:', inputValue);
    }
  };

  return (
    <input
      type="text"
      value={inputValue}
      onChange={(e) => setInputValue(e.target.value)}
      onKeyDown={handleKeyDown}
    />
  );
};

export default InputComponent;
Enter fullscreen mode Exit fullscreen mode

Key Types:
For forms: React.FormEvent
For inputs: React.FormEvent or React.KeyboardEvent, depending on the event

in case it's hard to understand let's dig in a bit more, you have a box to put them in when you're done. When you put the crayons back in the box, you do it in a special way, like only placing them when they’re clean.

Now, let’s think of a form on a webpage like that box, and your crayons are the words you type in. When you finish typing and hit the "submit" button (like closing the crayon box), the form says, "Wait! Before I close, let me check if everything is okay!"

The onSubmit is like that check. It makes sure everything is good before sending your words somewhere else. In programming, we give the form instructions on what to check. If you press a key, like "Enter," it’s like saying, "I’m done!" And the form will listen, and follow the rules we gave it on what to do next.

In TypeScript, we just explain the rules very clearly, like telling it, "Hey, form, when someone clicks submit, check this special way."

Top comments (0)