Event Binding in React TypeScript
Prerequisites
- Make sure you have installed Node.js version 16+.
- To follow along with this article, you’ll need a react project that is generated with Nx. If you haven’t done it yet, see this article.
You can still follow the article by creating components in your own way.
Let’s Start
Handling user events in React is slightly different from HTML. To demonstrate this, let’s create a component called Search
component. Run the following command to generate the component.
nx g c search --dir app/components
onClick
To handle the click
event, we can write as follows.
We use onClick
to handle the click
event. Note that we use camelCase for the event names. Be careful that at line number 9, only function reference is passed not function call. Which mean:
onClick={search} // do this
onClick={search()} // don't do this
Because we don’t want to call the function at the page load. We only want to call the function when the user click the button.
Call from App Component
Open app.tsx and write the following code.
Serve the Application
Run with nx serve
. And then got to http://localhost:4200
and click the button. You can see the log “Searching…” at the javascript console.
onBlur
To handle the blur
event, we can write as follows.
Same as the onClick
event but for the onBlur
event, we can receive the event
object with the type ChangeEvent<HTMLInputElement>
. We can also use the type for onChange
, onInput
, onFocus
etc.
onKeyUp
To handle the keyup
event, we can write as follows.
The event type is changed to KeyboardEvent<HTMLInputElement>
and to get the value
we need to type case as HTMLInputElement
. Of course, we can use the type for onKeyDown
event.
Done
By using this way, we can handle the various user events.