For enquiries call:

Phone

+1-469-442-0620

April flash sale-mobile

HomeBlogWeb DevelopmentHow to Create React Project with Typescript

How to Create React Project with Typescript

Published
05th Sep, 2023
Views
view count loader
Read it in
11 Mins
In this article
    How to Create React Project with Typescript

    In this article, we will be talking about creating a react project with TypeScript. Also, we’ll be talking about some important things that you should know about react and TypeScript.

    What is React?

    ReactJS is one of the most famous free and open-source UI libraries in the world. It’s implemented with JavaScript. But it is much easier to use than pure JavaScript. React JS is maintained by Meta. (formerly Facebook) React can be used to develop single-page web applications and mobile applications.

    The react js course on KnowledgeHut is useful if you are planning to learn more and get a well-recognized certificate on ReactJS.

    Why TypeScript?

    TypeScript is a programming language developed by Facebook. It’s a strict syntactical superset of JavaScript. Compared to JavaScript, TypeScript is a bit hard to use. But once you get used to it, TypeScript will be much easier and more helpful for your project. We’ll talk a bit deep about the pros of using TypeScript in a later part of this article.

    When to Use Typescript?

    Normally, we use JavaScript in a ReactJS project. But sometimes, we have to use TypeScript. And it depends on many factors such as,

    • Size of the codebase 

    When it’s a large project, using TypeScript is good, because it’s very easy to understand the code. Especially classes and models. Since they have types. For a small project, you can use JavaScript which is the default.

    • Team members’ understanding 

    Unlike JavaScript, TypeScript is a bit complex. So if you or your team is going to work with TypeScript, it is better to have a good understanding of TypeScript, before starting the project.

    • When there are a lot of type checks 

    There are some projects which have more and more type checks. For an example, 

    typeof name !== 'string' ? console.log(‘Name should be string’) : null 

    With TypeScript, you don’t need to use these kinds of checks. You can eliminate them.

    How to Use TypeScript with React

    Since we got a bit of understanding of ReactJS and TypeScript, let’s dive into the practical side. Here we will talk about how you can use TypeScript in your ReactJS project and about some cool features of TypeScript.

    Strongly-typed Function Component Props

    This is one of the abilities that TypeScript gives. You can give component props a type. This allows the developers to quickly understand the types of props that needed to be passed to this component. Let’s see how it’s done.

    In the First image depicts a simple react, JavaScript component.

    As you can see, we have defined just props. We haven’t defined the type of props. This is a bit confusing when the project gets a bit large, or when more team members are working on the project. So the best solution is to define a type for the props. So that anyone who looks at the code can easily understand what this is, and what to pass as props.

    There are a couple of ways of doing this. First I’ll show the Inline Type Annotation which is the easiest. So let’s see how we define strongly-typed function component props.

    As you can see, we have props and types of props defined within the component.

    The next way is to define the props with a type alias. What we do here is extract the props into a type alias and then extend the props with the defined alias. Let’s see how it is done.

    The advantage of this method is we can use the same prop type in different components which are having the same prop type. This method will be useful when the project gets bigger, so you can avoid code duplication.

    The Strongly-typed Context for Functional Components

    React offers a simple way for state management. It’s called context API. For the context API as well, we can use TypeScript. Let’s see how it’s done.

    A common usage of the context API is to change the theme of the application. So let’s stick with that scenario.

    As the first step, I’m gonna create the context file.

    The next step is to create the provider file with TypeScript. Let’s see how it’s done.

    As you can see here, we have defined a type alias and we have defined the prop type. Once we change the value of the currentTheme, the application will rerender the provider’s children with the new theme. 

    The next step is to create a custom hook. So that the components can consume our context.

    The next step is to add the context to the component tree. We can do that by modifying the App.tsx file as shown below. 

    Here we have wrapped our components with the ThemeProvider class. Now the context is added to the component tree.

    As the next and final step, you have to consume the context in the component. Let’s see how you can do that in the Header component.

    Likewise, you can use strongly-typed context in your functional components in ReactJS with TypeScript. See? So easy.

    Strongly-typed React Event Handlers

    One of the useful things in ReactJS is events. This event system is a wrapper around the web browser’s event system. @types/react npm package contains the TypeScript type for those events.

    There are a few types of ReactJS events. Let’s talk about those a bit more.

    1. Inline event handlers

    Inline events are used inside the render method. An example would be an onClick() Or an onChange() event. As you can see, when you use TypeScript, you can get better IntelliSense from the IDE.

    2. Named event handlers

    These types of events are used inside named functions. Let’s see an example.

    So here, we have a function called handleChange(). As you can see, the parameter is called ‘e’. And the type is any. Which is not good. Still, you won’t get any error since ‘any’ is a correct type. But it’s not suitable. A function should have a fixed input type. The onChange event of an input field is React.ChangeEvent<HTMLInputElement>. Let’s add that instead ‘e’.

    Great. Here’s how you can easily configure a named event handler.

    3. Cross element event handlers

    In a component, we might write more than one functions that use the same method. As an example, take a look at the below piece of code.

    As you can see, the type of the e is any. And it’s not good because we can pass any kind of value there. So what do we do?

    Well, as you can see, we have two element types using this onChange function. Input and a textarea. These two elements have two types. So what we are going to do is add both types instead any, with the or operator. Let’s see how it is done.

    Since we have added both HTMLInputElement and HTMLTextAreaElement the function now knows what to accept and what to reject. Even the developer is now aware of the values that are passing to this function.

    Strongly-typed Refs in Function Components

    React has many hooks. The ref is one of them. Ref is used to get all the properties and methods of an element.

    As you can see, inside the return statement, we have a <div>. To refer to this div, I have created a ref called ‘main_div’. And I have used HTMLDivElement as the ref type since it’s the type of the div.

    If you are interested in exploring ReactJS in depth, go ahead and explore React.js course KnowledgeHut. This will be a huge advantage for your career. 

    Creating a React Project with TypeScript

    Creating a react project is easy. We’ll discuss how to do that in this section.

    Step 1: Gather technical requirements

    First things first. Before starting anything, we need to gather requirements to finalize the tech stack of the project. As I mentioned before, TypeScript is good when the project is a large one. It’s not ideal to use TypeScript for a simple, small project. So do the requirement analysis, and decide what you need to use.

    Step 2: Set up React with Typescript

    To create a react project with TypeScript, you just need to extend the normal bash command with two keywords. Let’s see how it’s done.

    npx create-react-app my-app --template typescript 

    All you need to do is add --template typescript to the end of the command. Once the project is created, you can see the files are .tsx instead of .js. 

    Step 3 - Run the app

    React uses yarn instead of npm. So you can use the below yarn command to run the app. But that doesn’t mean you can’t use npm. I’ll add the npm command as well.

    yarn start  

    npm start 

    Is TypeScript Good for React?

    1. Readable, easily understandable code 

    Yes, JavaScript is easy to use. But as I mentioned, when the project is getting bigger and bigger, developers are going to get confused with the code. That’s the reason TypeScript is a good solution than JavaScript. People can easily tell what you need to pass to this component. So there will be less confusion and errors.

    2. Interfaces 

    In another word, Type Aliases. You can define the prop type in a class. And make it an interface. So that other components which have the same prop type can use the base class/ interface instead of defining their prop types. This reduces code duplication.

    3. Better support for JSX

    JSX means JavaScript XML. That means the HTML inside the react component. Here the support means the IntelliSense and the code completion. Not like JavaScript, TypeScript has better IntelliSense support. You should be able to see that when you are coding.

    4. IDE support

    Most famous IDEs are supporting TypeScript. Including Visual studio code, Atom, Vim, Storm ...etc.

    5. Support for existing React projects 

    You can use TypeScript with the existing react projects too. You just need to install the relevant libraries and simply rename a file. Let’s see how we can do that.

    For an existing react project, use 

    npm install --save typescript @types/node @types/react @types/react-dom @types/jest 

    6. Command to install TypeScript.

    Once the installation is done, all you have to do is rename the necessary files. That means you have to change the extension of the file. For example, you have the App.js file inside the src directory. Just rename it to App.tsx.

    Just like that, you can rename all the files. Once it’s done, you are all good to go with TypeScript.

    7. Community 

    Talking about the community, many developers use TypeScript with ReactJS. You could find various questions on Stack Overflow regarding ReactJS with TypeScript. Not only that, there are many more communities that share TypeScript knowledge. So, you should be good to go with learning and using TypeScript.

    Looking to master Python? Join our python online training program and unlock the power of this versatile language. Start coding like a pro today!

    Conclusion

    In this article, we have covered some important aspects of using TypeScript with ReactJS. We learned about strongly typed props, strongly typed refs, strongly typed event handlers, etc. Not only that, we learned how we can create a TypeScript based react project from scratch, and a bit of coding as well. I hope that you have gotten the some advance knowledge with this article regarding TypeScript and React. ct.

    If you are planning to master web development, web design and development course is one of the best options for you. Not only ReactJS, but this course also covers so many languages and frameworks like Angular, NodeJS, JavaScript, and Full stack web development.

    Frequently Asked Questions (FAQs)

    1Is TypeScript frontend or backend?

    Even though TypeScript is the superior version of JavaScript, when compiling TypeScript is converted to JavaScript. So, you can use TypeScript anywhere you have used JavaScript. So for the question, Yes you can use TypeScript in both front ends and back ends.

    2Is TypeScript a dev dependency?

    It’s not exactly a dev dependency. But you can categorize TypeScript as a dev dependency since it’s used for local development and when compiled, it’s converted back to JavaScript. Adding it as a dev dependency has some benefits. The version of the TypeScript you used is specified if you added it as a dev dependency.

    3How do I integrate TypeScript with React?

    With the below commands, you can create a fresh ReactJS project with TypeScript.

    yarn create react-app my-app --template typescript 

    or 

    npx create-react-app my-app --template typescript 
    4How do I use web workers with React.js and TypeScript in a Create-React app?

    You can achieve that with worker-loader and react-app-rewired. For more information on this, you can visit the GitHub page 

    Profile

    Gamage Ayesh Nipun Dinuranga

    Trainer & Consultant

    "My name is Ayesh Nipun, a Microsoft-certified Azure Developer, a Senior software engineer, and a blogger. I write blogs mainly on ReactJS, ASP.NET Core, and Microsoft Azure. And I'm having 3+ years of professional experience in software development and having 4 years of experience in freelancing. I have worked on both in-house and client-based projects again using many latest technologies like ReactJS, ASP.NET Core, SQL, and Azure. Some of my blogs have been published on Javascript in plain English and The Startup on medium.com. My Primary skills include ReactJS. ASP.NET Core/MVC, Microsoft Azure, Database management(SQL, NoSQL), Docker, K8s, Terraform, and CI/CD. You can visit my LinkedIn profile for more information about me or you can visit my Website at ayeshnipun.com"

    Share This Article
    Ready to Master the Skills that Drive Your Career?

    Avail your free 1:1 mentorship session.

    Select
    Your Message (Optional)

    Upcoming Web Development Batches & Dates

    NameDateFeeKnow more
    Course advisor icon
    Course Advisor
    Whatsapp/Chat icon