If you’re new to TypeScript or React, it might not be obvious how to pass a function to a button or another component to change the state of your current component. Due to JavaScript’s “this” binding, it can become very confusing. This guide will show you how TypeScript can make this easy. In doing so, we will build a simple app to change the color and text of a box with a button. This would be useful for a teacher who wants to know if their students are understanding the material.
Here is an example of how to create a Toggle Button for the user to click.
1import * as React from 'react';
2
3interface ToggleProps {
4 ClickHandler: (event: React.MouseEvent<HTMLButtonElement>) => void
5}
6
7export function Toggle(Props: ToggleProps) {
8 return <button onClick={Props.ClickHandler}>Toggle</button>
9}
In this component, we create an interface that defines what kind of props our Toggle component should receive. We are expecting only one prop called ClickHandler. It takes a function and returns void. As a sample reference, the ClickHandler prop function is currently set up to receive an event parameter of React.MouseEvent type that is applied to an HTMLButtonElement. Any time you click on an element in JavaScript with your mouse, it receives this event property by default. We won’t be needing it in our example. If you did need information about the mouse click event, this is how you would let TypeScript know about the type of event and the type of element that was clicked.
This guide has explained how to useto use a Toggle Button type component with a variety of other components. Each component can tell the Toggle Button what to do when clicked.
It should be noted that, in the above examples, you could have used a plain button component instead of creating a special Toggle component that wraps around the button. The Toggle component shows an extra layer of complexity when it comes to passing our toggleClickHandler method down multiple components. In this case, our toggleClickHandler gets passed to the Toggle component. The Toggle component then passes it to a plain button component. The whole time, our toggleClickHandler will remain connected to our StatusCard component when changing the state.