Join egghead, unlock knowledge.

Want more egghead? It's 45% off for a limited time only!

This lesson is for members. Join us? Get access to all 3,000+ tutorials + a community with expert developers around the world.

Unlock All Content for 45% Off

Already subscribed? Sign In

Save 45% for a limited time.

Get access to all courses and lessons on egghead today.

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