This Lesson is for Members

Subscribe today and get access to all lessons! Plus direct HD download for offline use, enhances transcripts, member comment forums, and iTunes "podcast" RSS feed. Level up your skills now!

Unlock This Lesson

Already subscribed? Sign In

Autoplay

    Create stateless React components using TypeScript

    Basarat Ali SyedBasarat Ali Syed

    You can create a stateless React component in TypeScript as easily as creating a function.

    But if you want to create high quality idiomatic React + TypeScript components we cover some improved patterns in this lesson.

    reactReact
    ^16.0.0
    typescriptTypeScript
    2.5
    Code

    Code

    Become a Member to view code

    You must be a Member to view code

    Access all courses and lessons, track your progress, gain confidence and expertise.

    Become a Member
    and unlock code for this lesson
    Transcript

    Transcript

    Basarat Ali Syed: 00:00 Here, I have a simple TypeScript application that renders the div Hello World! To the DOM using React and ReactDOM. We can easily move this div into a stateless component called App by creating a function called App and returning the same JSX element.

    00:24 Of course, one big advantage of components is that you get to use props that change the component behavior. For example, we can take the message as a prop by adding it as an argument and using it inside the function body. TypeScript tells us that this property needs to be provided, so we go ahead and provide it.

    00:45 Let's add something different this time. You can see that it works as expected. Although such simple functions work fine for stateless components, if you want to create high-quality types of components, it is recommended that you annotate such functions as React SFC.

    01:04 The React SFC interface takes a generic argument that allows you to easily provide the type annotation for the component props. You can see that the type specified over here flows through to the function arguments.

    01:21 Of course, if you want, you can easily move out this inline prop type definition into an appropriately named type, for example, App Props.

    Discuss

    Discuss