🎁

12 Days of Baddass Courses sale! Get instant access to the entire egghead library of courses and lessons for 58% off.

Runs out in:
11 : 17 : 25 : 28
Join egghead, unlock knowledge.

Want more egghead? It's 58% 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 40% Off
1×
Become a member
to unlock all features
Autoplay

    Write your first React TypeScript Component

    Shawn WangShawn Wang
    reactReact
    typescriptTypeScript

    In this lesson we start from an empty directory and bootstrap a React TypeScript app with create-react-app. Then we write our first React TypeScript Component and add our first types, including an optional type.

    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
    Discuss

    Discuss

    Transcript

    Transcript

    Instructor: Start with an empty directory. We're going to run Create React App with the TypeScript option. Once it's installed, you can see that your package.json has a bunch of types packages alongside your regular React packages.

    We're going to run Yarn Start just to show that this is a regular functioning app. You can see in app.tsx that there's not much difference between regular React and React with TypeScript. In fact, TypeScript is a superset of JavaScript, so this is to be expected.

    We're going to write our first component. It's going to be a function component. Here, we'll see the differences. I'm going to add a button component that's going to be a regular React function component. This is going to return a button with the default text of Hello World.

    I'm going to use that button component inside of my app, which is scaffolded by Create React App. I'll just delete all the old stuff that it's giving me by default. So far, we haven't written any TypeScript, but that's about to change.

    We'll take in some props for the button and we'll give types to the props. You can define the types in-line, but I prefer to define it separately because that scales better. We'll take a label prop and we'll declare it to be a type string.

    Instead of Hello World, we can just put props.label in there. If I save it right now, it's going to show an error. It expects a label prop, but it wasn't passed a label prop in the app.

    To solve that, you can actually pass a prop here as shown, or you can refactor this button component to take an optional prop by adding a question mark.

    That works as well, but there's no text inside the button. You might want to destructure it and add a default. You can do that just as you would in a regular React app, Hello TypeScript. That's how you write your first React and TypeScript component.