Adding Types To Events In React Using TypeScript

Solutions For Adding Types To Events In React Using TypeScript

Adding types to events in React using TypeScript is a simple task. To do it you can use event handler orUse alternative interfaces. Let’s see the below post to know the specific steps!

ReactJS Events

React is a Javascript-based library. There’s not much difference in event handling between ReactJS and Javascript. With Javascript, a function will be called to execute when an event occurs. But with React, a Component method is called when the event occurs. Here is an example:

Code:

export default function App() {
    function handleSubmit(e) {
      alert('You clicked the '+e.target.innerText+' button.');
    }
    return (
      <form onSubmit={handleSubmit}>
        <button type="submit" className="submit">Submit</button>
      </form>
    );
}

Output:

You clicked the Submit button.

When working with React, you usually don’t need to call addEventListener to attach a listener to the DOM element after it has been initialized. Instead, you must provide a listener the first time the element is rendered.

Install typescript into your project

TypeScript is an open-source project developed by Microsoft that is considered an enhanced version of JavaScript. Since it optionally adds static types and object-oriented classes, it includes ECMAScript 2015 (ES6).

Advantages:

  • Open source
  • Easy to develop large projects
  • Supports the latest JavaScript features
  • Strong OOP support
  • Clear code organization
  • Multiple Frameworks to choose from

Defect:

  • Must learn a new type of js
  • Bulky code
  • Add extra step – compile
  • It is not an actual statically typed language

Terminal:

# Run the following command to install:
npm install -g typescript
# To create .js files from .ts files:
tsc fileName.ts

Adding Types to Events in React using TypeScript 

Use event handler

You can follow the example below to see how to add types to events in React using TypeScript.

Syntax:

event : type<HTMLelement>

Parameters:

None

Code:

import {MouseEvent } from 'react';
export default function App() {
    function handleSubmit(event: MouseEvent<HTMLButtonElement>) {
      alert('You clicked the submit button.');
    }
    return (
      <form onSubmit={handleSubmit}>
        <button type="submit" className="submit">Submit</button>
      </form>
    );
}

The element in the DOM will be added a function handler to catch the event with the element. In this example, the handleSubmit function is created to handle the event submission of the form. With typescript, we add MouseEvent to catch the click event of submit button.

Use alternative interfaces

You can use the object’s built-in EventHandler property to “catch events”. You then assign the value of the event to an alternative interface. Check out the example below to learn more about this.

Code:

import { ChangeEventHandler} from 'react';
export default function App() {
    function handleOnChange(event: ChangeEventHandler<HTMLInputElement>) {
      console.log(event.target.value);
    }
    return (
      <form >
        <input className="name--input" placeholder="Enter your name" onChange={handleOnChange}></input>
      </form>
    );
}

In this example, the onChange attribute is used to print the value of the target event to the console log when the user changes the value in the input box. To do that, we have to use alternative interfaces, specifically in the above example, we use ChangeEventHandler.

Summary

To summarize, this article shows us the best solution for adding types to events in React using TypeScript. You can create an event handler and catch the event using TypeScript.

Maybe you are interested:

Leave a Reply

Your email address will not be published. Required fields are marked *