Configure TypeScript for React and JSX

John Lindquist
InstructorJohn Lindquist
Share this video with your friends

Social Share Links

Send Tweet
Published 6 years ago
Updated 3 years ago

TypeScript and React go very well together, but it does require a little bit of configure on the TypeScript side due to the nature of JSX. The compiler option for JSX just needs to be set to "react" in the tsconfig.json and you're on your way.

Instructor: [00:00] To use TypeScript with React, I'm going to change the extension on this to TSX, meaning that file will use JSX. I'm going to change the extension here to TSX as well, add a place to drop my React app, then create a React app really quickly. Import React, then Import Render, Create an App, and render out the app into my element.

[00:29] Once I run parcel again, you'll see it will install React and the necessary dependencies because it automatically installs missing dependencies.

[00:40] If I open the server -- one, two, three, four -- you should see an error saying that it's missing React and React is not defined, which you can either solve by changing the way React is imported by saying Import Everything as React, because of a minor difference between the way JavaScript and TypeScript take that default Import. You can see that that solved it.

[01:04] If you want to keep that default in place, we'll break it again, and you'll see this is not working. You can create what's called a tsconfig.json. I'll create some JSON for it, Autocomplete Compiler options, and then Autocomplete JSX, and set that to React.

[01:25] Then I will need to stop my build, remove the cache -- there's a hidden cache directory with my parcel files in there -- and then restart parcel, so that it picks up my configuration changes. Now, when I refresh, everything should be working again.

[01:41] You can keep React imported that same way as you would your normal JavaScript project by defining in your tsconfig how to handle JSX. In this way, TypeScript will keep React in scope.

[01:53] The other thing to notice are these three tiny dots right here, suggesting that you can hit Command Period to take suggested actions from VS Code.

[02:01] I'm going to choose install all missing type packages, because the types for React and ReactDOM are hosted at an @types organization on NPM. You'll see it will automatically add those to your dev dependencies here.

[02:18] Now, in this file, nothing's going to change over here. When you try and do something invalid -- for example, if I create a class of app and extend react.component, I say Render, and I don't return anything -- if I go over to my Problems, they'll tell me why those lines are red.

[02:37] This one essentially explaining, you need to return something from Render. I'll return my div of hi again and then the problems go away.