Skip to content

Contact sales

By filling out this form and clicking submit, you acknowledge our privacy policy.

How to Use React.js Components with Typescript

Jun 29, 2020 • 5 Minute Read

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:

      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.

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

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

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

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

        const myStyle: React.CSSProperties = {
            backgroundColor: 'blue',
            border: '1px solid red'
        }
        
        const MyComponent: React.SFC = () => <div style={myStyle}>Hello</div>
        
        • 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.

          class MyComponent extends React.Component {
             // The React.Component type is inferred
          }
          

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:

      interface MyComponentProps {
  name: string
}
    

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

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

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

      interface MyComponentState {
  // ...
}

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

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:

      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>
  }
}
    

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.