0

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,

import React,{ useState } from 'react';

interface Props {
    count : number,
    setCounter : () => void
}

const Counter : React.FC<Props> = ({
    count,
    setCounter
}) => {

    return (
    <div>
        <p>Count is ${count}</p>
        <button onClick={setCounter}>Add</button>
    </div>)
}

export 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.

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

interface Props {
    count? : number,
    setCounter : () => void
}

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.

import React,{ useState,useEffect } from 'react';
import Counter from './Counter';

const App: React.FC = () => {

  const [state,setState] = useState<number>(0);

  const incrementCounter = () => {
    setState(state+1)
  }

  return (
    <div className="App">
      <header className="App-header">
         <Counter count={state} setCounter={incrementCounter}/>
      </header>
    </div>
  );
}

export 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.

const [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

const 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.

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

const 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.

import React,{ useState } from 'react';

interface Props {
    children : (
        x : number,
        y : number
    ) => JSX.Element | null
}

const Mouse : React.FC<Props> = ({children}) => {

    const [state,setState] = useState({
        x : 0,
        y : 0
    })

    const handleMouseMove = (event : React.MouseEvent<HTMLDivElement, MouseEvent>) => {
        setState({
            x : event.clientX,
            y : event.clientY
        })    
    }

    return (
        <div style={{ height: '100%',position: 'relative' }} onMouseMove={handleMouseMove}>
            { children(state.x,state.y) }
        </div>
    )
}

export 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.

const handleMouseMove = (event : React.MouseEvent<HTMLDivElement, MouseEvent>) => {
        setState({
            x : event.clientX,
            y : event.clientY
        })    
    }

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

import React from 'react';

interface Props {
    x : number,
    y : number
}

const Cat: React.FC<Props> = ({ x,y }) => {
    return (<img src={require("./sample.png")} style={{ left: x,top : y,position: 'absolute' }}/>)
}

export 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 🙂

ganeshmani009

Leave a Reply

Your e-mail address will not be published. Required fields are marked *