DEV Community

Cover image for Dummies for React and Typescript
hillkim
hillkim

Posted on • Updated on

Dummies for React and Typescript

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 πŸ‘Œ

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

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

If you are yarn religious like me, smile and go with πŸ˜‹

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

Here is a lengthy show of the same
asciicast

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 πŸƒπŸ»β€β™‚οΈ

yarn start

or

npm run start

Hit http://localhost:3000/ and you should be seeing this
Alt Text

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

//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

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 πŸ™πŸΌ

//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?

interface DummyComponentProps {
  //
}

In typescript, interface 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 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

//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

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

import React, {FC} from 'react'; 

Ok! πŸ˜‡
Since our component render props are defined, we can now use the interface as a reference in

React.FC<DummyComponentProps>

πŸ‘Š
By now you should be seeing the autocompletion magic as we destructure our props
Alt Text

Pheew!!
Lets now add more guts (flesh out!) to our component body. It should look like this

//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

//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

But we know what the component needs. So we give it!

 <DummyComponent name="DumDum" age={120} isSad/>

VoilΓ !!
Alt Text

What if we need to make some props optional?

Just add ? in the definition
Here the isSad prop is optional

//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

//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

<DummyComponent name="DumDum" age="one hundred and twenty" isSad={false}/>

And here we go!
Alt Text

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! 🀝

Top comments (0)