Class components with TypeScript

Here is what a React class component looks like with TypeScript:

import React, {Component} from 'react'; 
 
type Props = {}; 
type State = {}; 
 
export class HelloWorld extends Component<Props, State> { 
    render() { 
        return <span>Hello World!</span> 
    } 
} 

Now that we can use TypeScript, we can, of course, start adding typesgreat! The first thing that we did in the preceding example was define the shape of the props object and the state. In this basic example, these are empty though.

We have used a custom type rather than interface mainly for conciseness (there is simply less code to type). Type aliases are a good fit with React thanks to their composability.

Our component extends the Component class and uses its generic type arguments to pass our Props and State types, allowing TypeScript to give us autocompletion and type checking within the class.

One thing that you should notice is that we did not use a constructor to define the initial state/props. There is already a constructor in the superclass and, usually, we won't need to create a constructor ourselves. React handles the instantiation of the components so we don't need to take care of that ourselves.

Great—let's continue.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
3.147.104.120