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.
Instructor: [00:00] 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.
[00:33] 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.
[00:51] 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.
[01:06] 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.
[01:22] 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.
[01:35] 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.
[01:49] 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.