Dummies for React and Typescript
Tags: typescript, react, codequality, javascript
Published: 2020-04-29 21:02:53

I know there is a whole lot of resources on typescript and react out there....Cut it! Why write another one? Right! Because someone needs it. I won't waste any page space trying to feed my fellow noobs with pros and cons of the TS and React combo. How the hell do I get to use typescript with react without reading and watching too much? Well... here is how!

No time for coding along? [Just clone the repo and get going already 👌](https://github.com/hillkim/react-typescript-dummy)

# Starting a new Project
Since CRA(Create-React-App) supports typescript, we will use it(We are all lazy! 🤫). This does not mean you are limited to CRA. If you feel confident enough, you can as well use *webpack* and *babel* (After a few trips to stackoverflow and github 🤡) but that is behold the scope of what my fellow noobs need.

Okey let's go....
 
Open terminal and kindly type
```sh
npx create-react-app my-dummy-project --template typescript
```
If you are yarn religious like me, smile and go with 😋

```sh
yarn create react-app my-dummy-project --template typescript
```

Here is a lengthy show of the same
[![asciicast](https://asciinema.org/a/dy67QbGu5dXER522kltRE07d7.svg)](https://asciinema.org/a/dy67QbGu5dXER522kltRE07d7)

Woosh! That was long!😰

# Celebrating your creation🤩 
Now that you have ticked all the magical boxes of project creation, you can proudly open the project folder using your favorite Code Editor. I am sorry if you don't use VS code because that's what bonafide **TS/JS** fanboys/fangirls use *(strong opinion alert!)*.

### 💡
As you have noticed, the normal *.js* and *.jsx* have been replaced to favor *.ts* and *.tsx* . This is a confirmation of typescript presence in the scaffold 🧪!

### Let's Run 🏃🏻‍♂️
```sh
yarn start
```
or 
```sh
npm run start
```

Hit **http://localhost:3000/** and you should be seeing this 
![Alt Text](https://dev-to-uploads.s3.amazonaws.com/i/twahf9bi07wjj05pvfy3.png)

Perfect! If you are at this point, then you are ready to get your hands typescript kind-of dirty! 🔥
Let's try change something on **App.tsx**

```js
//App.tsx
import React from "react";
import logo from "./logo.svg";
import "./App.css";

const App = () => (
  <div className="App">
    <header className="App-header">
      <img src={logo} className="App-logo" alt="logo" />
      Dummy Trying To Typescript 🤪
    </header>
  </div>
);

export default App;
```
Boom 💥
![Alt Text](https://dev-to-uploads.s3.amazonaws.com/i/obdvpuz7j1ifgukz8jqi.png)

## Adding a new component (With typed props 😍)
Since the whole hassle of having typescript presence at all is not to replace JavaScript, then we should make it do sh*t for us. The sweetness of type safety and the enticing errors right on the code editor(Don't get me started 🥺!) can be witnessed right on the spot. Let's try it out.

Create a file in *src/* folder 
 **DummyComponent.tsx**
Please copy and paste this code to the component 🙏🏼
```js
//DummyComponent.tsx

import React from "react";

interface DummyComponentProps {
  //
}

const DummyComponent: React.FC<DummyComponentProps> = () => {
  return <div>This is my Dummy Component!</div>;
};

export default DummyComponent;

```
## What is this!? 🙄
I know right! Let me break it down for you. 
The first line is the usual react import. And yes that's not the point.
So what the hell is going on in this snippet?
```js
interface DummyComponentProps {
  //
}
```
In typescript, [*interface*](https://www.typescriptlang.org/docs/handbook/interfaces.html) is a key word that is used to create allowed type definitions or contracts. Our dummy component is going to abide by the types we define here. For those of us dummies who have used [PropTypes](https://reactjs.org/docs/typechecking-with-proptypes.html) before, our  **DummyComponentProps** will help us achieve type checking with ease.

Why are we even doing this? *We want to make sure what we pass as props to our dummy components is not what we think they want but what they exactly need*. For example avoiding passing *numbers* where a *string* or *boolean* is required! See.... this is easy 🤗

Let's edit our component to add props 
```js
//DummyComponent.tsx

interface DummyComponentProps {
  //renders dummy name
  name: string;
  // renders dummy age
  age: number;
  //renders sad dummy 
  isSad: boolean;
}
```
As you can see we have explicitly stated the type of values that the dummy component can tolerate as render props. Aha!😁 

## So how do we use our new super powers on the dummy component 🤔?
Here is how
```js
const DummyComponent: React.FC<DummyComponentProps> = ({name, age, isSad}) => {
  return <div>This is my Dummy Component!</div>;
};

```
What we have done...
Our dummy component is typed with a **React.FC<>** generic type that comes with react type definitions! Yes! I said it! Basically, this is to say that react has types defined to help us define our components with reference to these properties. Our component is typed to be a functional component (hence **FC**).We can actually import this separately from react itself 
```js 
import React, {FC} from 'react'; 
```
Ok! 😇 
Since our component render props are defined, we can now use the interface as a reference in 
```js
React.FC<DummyComponentProps>
```
👊
By now you should be seeing the autocompletion magic as we destructure  our props 
![Alt Text](https://dev-to-uploads.s3.amazonaws.com/i/kb9hs9s0rfnoq3fai95t.png)

Pheew!! 
Lets now add more guts (flesh out!) to our component body. It should look like this
```js
//DummyComponent.tsx
import React from "react";

interface DummyComponentProps {
  //renders dummy component name
  name: string;
  // renders dummy age
  age: number;
  //renders sad dummy component
  isSad: boolean;
}

const DummyComponent: React.FC<DummyComponentProps> = ({
  name,
  age,
  isSad,
}) => {
  return (
    <div>
      <h1>I am {name}</h1>
      <h2>I am {age} years Old</h2>
      <p>{isSad ? "😔" : "😀 "}</p>
    </div>
  );
};

export default DummyComponent;

```
We are done!

Sorry, not yet! We need to use our component! 🙀

## Making use and witnessing instant benefits of typescript 🥰

Let's update our **App.tsx** to have a dummy child component.

 😈 Now let's add this
```js
//App.tsx

import React from "react";
import logo from "./logo.svg";
import "./App.css";
import DummyComponent from "./DummyComponent"


const App = () => (
  <div className="App">
    <header className="App-header">
      <img src={logo} className="App-logo" alt="logo" />
      Dummy Trying To Typescript 🤪

       <DummyComponent />  {/* 😡 */}
    </header>
  </div>
);

export default App;

```
Typescript with automatically be like 😡
![Alt Text](https://dev-to-uploads.s3.amazonaws.com/i/geat5dzt7nqdmgufku76.png)

But we know what the component needs. So we give it!
```js
 <DummyComponent name="DumDum" age={120} isSad/>

```
Voilà!!
![Alt Text](https://dev-to-uploads.s3.amazonaws.com/i/kkywbr08fmcxbpxms2c9.png)

## What if we need to make some props optional?
*Just add ? in the definition* 
Here the **isSad** prop is optional 
```js
//DummyComponent.tsx

interface DummyComponentProps {
  //renders dummy component name
  name: string;
  // renders dummy age
  age: number;
  //renders sad dummy component
  isSad?: boolean; // 👈
}
```

## ....And What if we need to have a prop with more than one data type?
Say no more!
We can allow age to be a string or a number
```js
//DummyComponent.tsx

interface DummyComponentProps {
  //renders dummy component name
  name: string;
  // renders dummy age
  age: number | string; // 👈
  //renders sad dummy component
  isSad?: boolean;
}
```
For instance when we want to render *I am one hundred and twenty years old*
We just update

```js
<DummyComponent name="DumDum" age="one hundred and twenty" isSad={false}/>
```
And here we go!
![Alt Text](https://dev-to-uploads.s3.amazonaws.com/i/gwlb9o0qcc10xv5hk9v4.png)

## Wrapping Up!
Typescript is such a great tooling for a javascript developer. It gives one the power to make softwares with deterministic behavior, not to mention the confidence to refactor large code bases without facing mayhem 😉 . That's all folks! Y'all clear. No one is a dummy now 😎 

This is my first article. Please be nice! If you have a job offer please holla as well. Thanks! Be safe! 🤝