TypeScript for React developers in 2020

In this article, we will see how to use typescript in react applications. TypeScript for React developers in 2020.

Recent Articles,

React packages that improved my productivity in 2019

Configuring babel for Node.js/Express Server

If you are completely new to the concept of typescript, i recommend you to read this article and continue further.

you may ask, why it is mentioned react specifically,Will knowing just typescript not enough?.

well, that's more than enough. but, knowing how to use with React is also important in fact.

That's what we are see in this article. there are three important things to know about using TypeScript in React. they are,

  • Typecheck for Props in React Component.
  • React Hooks Type Check.
  • TypeCheck for Render Props in React.

Props TypeCheck in React

Firstly, an important things is to type check the component props in react. For Example,

1import React, { useState } from "react"
2
3interface Props {
4 count: number;
5 setCounter: () => void;
6}
7
8const Counter: React.FC<Props> = ({ count, setCounter }) => {
9 return (
10 <div>
11 <p>Count is ${count}</p>
12 <button onClick={setCounter}>Add</button>
13 </div>
14 )
15}
16
17export default Counter

Here, we check the type of component Counter using interface in typescript. Once you define the type check for a component.

Whenever the component is used in any other components. it will expect the props and same type for the props. For Example, Here we defined the props count type as number.

So, it will expect the count prop type to be number. Also, props cannot be null.

Screenshot 2020 01 05 at 11 12 22 AM

If you want to make the props as an optional, you can define it with question mark like,

1interface Props {
2 count?: number
3 setCounter: () => void
4}

React Hooks TypeCheck

After that, React Hooks is an important one to check the type using TypeScript.

useState

Type check on useState is somewhat similar to what we have seen in Props.

you can typecheck the variable that you have defined in the state of react.

1import React, { useState, useEffect } from "react"
2import Counter from "./Counter"
3
4const App: React.FC = () => {
5 const [state, setState] = useState<number>(0)
6
7 const incrementCounter = () => {
8 setState(state + 1)
9 }
10
11 return (
12 <div className="App">
13 <header className="App-header">
14 <Counter count={state} setCounter={incrementCounter} />
15 </header>
16 </div>
17 )
18}
19
20export default App

Here, we check the type of state as number. it will throw an error if it is a string.

sometimes, the value can be null or undefined. typescript will throw an error for that as well. To fix that, you can also define the type as null as well.

1const [state, setState] = useState<string | null>(0)

useRef

useRef is little bit tricky on using with TypeScript. Let's consider that you a reference for a button

1const buttonref = useRef(null)

What will be the type of ref here. well, there is a trick here. Thanks to Ben Award for showing this trick.

That is to say, when you hover over the DOM Element, you can see the details about it. From there, you can get the type of that element.

Screenshot 2020 01 05 at 11 25 39 AM

So, use the same type in your ref hooks, like

1const buttonref = useRef<HTMLButtonElement>(null)

Render Props

Render Props is an important and hot topic in react patterns. If you're new to the concept of render props, i recommend you to read this article.

we will see how to add the type check for render props using the same example which is in react docs.

In short, we are going to get the mouse position and move an image based on the mouse movement.

Firstly, we will create a component called Mouse and add the following code.

1import React, { useState } from "react"
2
3interface Props {
4 children: (x: number, y: number) => JSX.Element | null
5}
6
7const Mouse: React.FC<Props> = ({ children }) => {
8 const [state, setState] = useState({
9 x: 0,
10 y: 0,
11 })
12
13 const handleMouseMove = (
14 event: React.MouseEvent<HTMLDivElement, MouseEvent>
15 ) => {
16 setState({
17 x: event.clientX,
18 y: event.clientY,
19 })
20 }
21
22 return (
23 <div
24 style={{ height: "100%", position: "relative" }}
25 onMouseMove={handleMouseMove}
26 >
27 {children(state.x, state.y)}
28 </div>
29 )
30}
31
32export default Mouse

Let's see what we are doing here. As always, we create a functional component and define a type check for it.

After that, we define the types for Props which is an interface. The small change here is, we define a function named children which takes the x and y as an input.

we define the type for x and y as well. since, it is a function we also need to define the return type for it. Here, it is a JSX Element. so, define that as well.

Next, important thing to notice here is, we have a onMouseMove event handler. since, it is a function. we need to define the type for that as well.

1const handleMouseMove = (
2 event: React.MouseEvent<HTMLDivElement, MouseEvent>
3) => {
4 setState({
5 x: event.clientX,
6 y: event.clientY,
7 })
8}

Since it is an event, like we said in the beginning of the article. you can get the type of DOM element on hovering it.

After that, create a component called Cat and add the following code

1import React from "react"
2
3interface Props {
4 x: number
5 y: number
6}
7
8const Cat: React.FC<Props> = ({ x, y }) => {
9 return (
10 <img
11 src={require("./sample.png")}
12 style={{ left: x, top: y, position: "absolute" }}
13 />
14 )
15}
16
17export default Cat

Above code is similar to what we have discussed so far.

So far, we have see the important things in react that we need to know for using TypeScript in it.

we will see more in depth topics of TypeScript in React in upcoming articles.TypeScript for React developers in 2020

Until then, Happy Hacking As Always :-)

Author

Hey, I’m Ganesh, Full stack engineer.I love to write technical content and help developers like me to grow in the industry. please consider supporting me.

To Read More

Building a Production-grade Nodejs,...

This article is the first part of building a production grade nodejs,graphql and...

Modern React Redux Tutorials with R...

This tutorial explain how you can build an application using modern react redux ...

Building a Piano with React Hooks

In this article, we will see how to build a piano with react hooks. Building a P...

TypeScript Basics - The Definitive ...

In this article, we will learn some basics of typescript which helps you to deve...

Here's why podman is more secured t...

In this article we will see about podman and why it is more secured way to run c...

Building a Production - Ready Node....

In this article, we will see how to build a Nodejs, TypeScript Application and d...

Nginx for Front-end Developers

This article is to explain Nginx for Front-end Developers in a much simpler way....

What is gRPC ? How to implement gRP...

Everyone talks about gRPC. Have you ever wonder how it works or how to implement...