Author avatar

Chris Parker

How to Use React.js Components with Typescript

Chris Parker

  • Jun 29, 2020
  • 5 Min read
  • 1,240 Views
  • Jun 29, 2020
  • 5 Min read
  • 1,240 Views
Web Development
Front End Web Development
Client-side Framework
React

Introduction

React and Typescript are magic together. Typescript provides the necessary tools to define strict types for the React components in your apps along with their props, states, and event handlers. This guide provides a shortcut on getting started with React and Typescript along with useful hints and smart strategies to combine the two.

Setting up a New Project

Getting started with a new JavaScript stack can be a bit frustrating. The available options are abundant, and you have to pick the right tools and then learn to compile them successfully together.

However, when it comes to using React with Typescript, you can easily use the famous React starter project: create-react-app. Thus, to create a new project, all you have to do is install the create-react-app CLI as follows:

1
2
npm install -g create-react-app
create-react-app my-app --scripts-version=react-scripts-ts

There you have it. The above command creates a new React app for you, wrapped with Typescript in a new folder named my-app. In order to run the app, move to the my-app folder and run npm start.

Employing React’s Type Definitions

React provides various type definitions that you can use in your app whenever you create a new React component.

  1. Use React.SFC when you define functional components.

    1
    const MyComponent: React.SFC = () => (<div>Hello!</div>)
    javascript

    A function defined by stateless functional component (SFC) returns a JSX element.

  1. Use the React.ReactChild return type when you want to include other renderable elements, such as strings or numbers.

    1
    2
    3
    4
    5
    // This is not allowed
    const MyComponent: React.SFC = () => 'Hello'
    
    // This is allowed
    const OnlyRenderable = (): React.ReactChild => 'Hello'
    javascript
  1. Use the React.CSSProperties type when you wish to define style objects.

    1
    2
    3
    4
    5
    6
    const myStyle: React.CSSProperties = {
        backgroundColor: 'blue',
        border: '1px solid red'
    }
    
    const MyComponent: React.SFC = () => <div style={myStyle}>Hello</div>
    javascript
  1. You do not have to include any additional type definitions when you use class-based components since Typescript deduces the type from the class definition of the inherited React.Component.

    1
    2
    3
    class MyComponent extends React.Component {
       // The React.Component type is inferred
    }
    javascript

Defining Types for Props and State

The best thing about Typescript is that it completely eliminates React’s PropTypes. Now, you can simply assert your prop types in Typescript. For instance, to create a prop interface for your React component that has a singular name attribute, check the following:

1
2
3
interface MyComponentProps {
  name: string
}
javascript

Now, you can use your interface as a type variable in the React.SFC type to assert the prop type for your component:

1
2
3
const MyComponent: React.SFC<MyComponentProps> = ({ name }) => {
  return <div>Hello {name}</div>
}
javascript

Likewise, add prop and state types for class-based components:

1
2
3
4
5
6
7
8
9
interface MyComponentState {
  // ...
}

class MyComponent extends React.Component<MyComponentProps, MyComponentState> {
      render() {
        return <div>Hello {this.props.name}</div>
      }
}
javascript

Defining Event Handlers for Elements

The React type library similarly offers type declarations for different event handler types. Usually, the event handler type definition relies on the answers to two major questions:

  1. What type of event are you using?
  2. What type of element are you interacting with?

If you wish to include an onClick event handler to your div element, you must set the element type to HTMLDivElement and the event type to React.MouseEventHandler as follows:

1
2
3
4
5
6
7
8
class MyComponent extends React.Component<MyComponentProps> {
  public myHandler: React.MouseEventHandler<HTMLDivElement> = (e) => {
    // do something
  }
  public render () {
    return <div onClick={this.myHandler}>Hello {this.props.name}</div>
  }
}
javascript

You can look here for details and a complete list of event attribute types and their corresponding events.

Conclusion

This guide is a good starting point for using React with Typescript. Although not each and every type that React offers is covered, you can experiment with what you learned here and dig deeper for the special cases you may come across.

2