So you know a Typescript but want to know how to use it with React. The following section will go through the basics of using TS with both class and function components.
For the following examples, we're going to be creating a
box component. The box can have a
width and a
height. as well as an
onClick method. We're using a super simple example here so we can focus on more the Typescript 💪.
Firstly we use Typescript to define the types of
state that our components can use. We define these like so:
These tell React that our Box component will only accept a
height that are
numbers and an
onClick function that does not return anything. Our state will also only contain a
name that will be a
Now this may not seem like a big deal, but it means that there is no guessing what sort of props we can pass to our components when we come to use them in the future!
Once we've defined what our
state are going to look like, we can add them to the component. To do this we can use the
<> notation alongside the
Component class from
Now when we try to use the component and pass in a
string as the
width instead of a number, we will get a nice type error telling us that our component is expecting
width to be a
number, not a
Now that we've mastered using Typescript with Class components, lets move on to my personal favourite, Function components.
Lets say we create a function component that represents out
Now already we can see much code we save on when using a Function component instead of a class component! But thats a topic for another post 😉
Using the same type's that we defined before, we can integrate them like so:
Now remember that Function components don't have state like class components but we can use the
useState hook to change that. The cool thing about the
useState hook is that it will use the type of whatever we pass into the method. So in this case
name will be a
Today we've learned how to use Typescript alongside React to make your components more reusable with both Class and Function components 🚀.
Thanks for reading and I hope you got something out of it. Since this is my first post ever, I'd love some feedback so feel free to throw some at me in the comments section below 👍!