Skip to main content

React with Typescript

The fun is starting! In this section I will try to explain all the need-to-knows about React and Typescript, combined!

Setup

First go where you want to be developing, and create a new next-app using the following command:

npx create-next-app@latest --ts

Open the project in VSCode, run yarn dev and open /pages/index.tsx in the editor.

Also open your browser on localhost:3000. This should show your newly created Next.js React TypeScript site!

Explaining all the new stuff

As you can see in this file, there's a lot of new stuff for us! This is TypeScript based React. I have copied the file inhere and will explain what everything means using comments.

/*
* In typescript, a comment can be written in multiple ways...
* This is a multiline comment
*/

// this is a one-line comment

// ok, so let's get started!

// here, we're importing certain functions, types and components from other files.
// These files can be located in packages and in our repo. More about this later.
import type { NextPage } from "next";
import Head from "next/head";
import Image from "next/image";
import styles from "../styles/Home.module.css";

/*
Here we declare a new constant variable called "Home". It is of type NextPage.
It is a function that seems to take no arguments, and returns a React Component
This is also called a functional component.
You may also not be familiary with the way this function is created.
This is an arrow function. The syntax is `const variable: Type = (...parameters:Type) => { return xyz };`
You can also see the exact type interface if you hover over NextPage in your VSCode Editor. Try it.
*/

const Home: NextPage = () => {
return (
<div className={styles.container}>
{/*This is the last way of commenting inside of typescript files. It only works inside of variables*/}
<Head>
{/* In Next.js we have something called a Head component.
This replaces the html head tag, because in Next.js we don't need to put the <html>, <head>, <body> everywhere.
Next's <Head> can be placed anywhere */}

<title>Create Next App</title>
<meta name="description" content="Generated by create next app" />
<link rel="icon" href="/favicon.ico" />
</Head>

{/* Everything below seems like the HTML like we've learned in the previous chapter.

However... there are some key differences!

For one, we're not using class here, but className.
This is because Typescript doesn't like class, class is a reserved keyword in Typescript.
That's why React changed the name so the HTML could be used within a Typescript envrionment. */}

{/* Below we see a main tag. In this page there's also a code tag and a footer tag.
These are other html tags I didn't tell you about.
It's not that common so forget it ;) */}

<main className={styles.main}>
<h1 className={styles.title}>
Welcome to <a href="https://nextjs.org">Next.js!</a>
</h1>

<p className={styles.description}>
Get started by editing
<code className={styles.code}>pages/index.tsx</code>
</p>

<div className={styles.grid}>
<a href="https://nextjs.org/docs" className={styles.card}>
<h2>Documentation &rarr;</h2>
<p>Find in-depth information about Next.js features and API.</p>
</a>

<a href="https://nextjs.org/learn" className={styles.card}>
<h2>Learn &rarr;</h2>
<p>Learn about Next.js in an interactive course with quizzes!</p>
</a>

<a
href="https://github.com/vercel/next.js/tree/canary/examples"
className={styles.card}
>
<h2>Examples &rarr;</h2>
<p>Discover and deploy boilerplate example Next.js projects.</p>
</a>

<a
href="https://vercel.com/new?utm_source=create-next-app&utm_medium=default-template&utm_campaign=create-next-app"
className={styles.card}
>
<h2>Deploy &rarr;</h2>
<p>
Instantly deploy your Next.js site to a public URL with Vercel.
</p>
</a>
</div>
</main>

<footer className={styles.footer}>
<a
href="https://vercel.com?utm_source=create-next-app&utm_medium=default-template&utm_campaign=create-next-app"
target="_blank"
rel="noopener noreferrer"
>
Powered by{" "}
<span className={styles.logo}>
{/* There's another important thing to mention here. Instead of <img>, in Next.js we'll need to use their <Image> component.
We need this because Next.js made many improvements on the <img> tag from HTML and put it in their own component.
It's much better! Check https://nextjs.org/docs/api-reference/next/image if you want to know why... */}
<Image src="/vercel.svg" alt="Vercel Logo" width={72} height={16} />
</span>
</a>
</footer>
</div>
);
};

// here, the newly created Home component is being exported so other files can find it.

export default Home;

Wow. That was a lot of info.... So what now?

  • I'm going to explain you the basics of Typescript.
  • Then the basics of React.
  • Then the basics of Next.js

Typescript Basics

I'm going to tell you more about variables, logging, primitive types, string literals, operators, comparisons, typeof and creating your own types. I'll do this by creating a script that you can copy and paste into your /pages folder.

Before that... Please paste this into your /pages/index.tsx. I've done a couple changes so you can navigate to this new page that we're going to create. Can you see what I did?

/*
* In typescript, a comment can be written in multiple ways...
* This is a multiline comment
*/

// this is a one-line comment

// ok, so let's get started!

// here, we're importing certain functions, types and components from other files.
// These files can be located in packages and in our repo. More about this later.
import type { NextPage } from "next";
import Head from "next/head";
import Image from "next/image";
import styles from "../styles/Home.module.css";
import Link from "next/link";

/*
Here we declare a new constant variable called "Home". It is of type NextPage.
It is a function that seems to take no arguments, and returns a React Component
This is also called a functional component.
You may also not be familiary with the way this function is created.
This is an arrow function. The syntax is `const variable: Type = (...parameters:Type) => { return xyz };`
You can also see the exact type interface if you hover over NextPage in your VSCode Editor. Try it.
*/

const Home: NextPage = () => {
return (
<div className={styles.container}>
{/*This is the last way of commenting inside of typescript files. It only works inside of variables*/}
<Head>
{/* In Next.js we have something called a Head component.
This replaces the html head tag, because in Next.js we don't need to put the <html>, <head>, <body> everywhere.
Next's <Head> can be placed anywhere */}

<title>Create Next App</title>
<meta name="description" content="Generated by create next app" />
<link rel="icon" href="/favicon.ico" />
</Head>

{/* Everything below seems like the HTML like we've learned in the previous chapter.

However... there are some key differences!

For one, we're not using class here, but className.
This is because Typescript doesn't like class, class is a reserved keyword in Typescript.
That's why React changed the name so the HTML could be used within a Typescript envrionment. */}

{/* Below we see a main tag. In this page there's also a code tag and a footer tag.
These are other html tags I didn't tell you about.
It's not that common so forget it ;) */}

<main className={styles.main}>
<h1 className={styles.title}>
Welcome to{" "}
<a href="https://codefromanywhere.com/">Code From Anywhere</a>
</h1>

<p className={styles.description}>
Get started by editing
<code className={styles.code}>pages/index.tsx</code>
</p>

<div className={styles.grid}>
<a href="https://nextjs.org/docs" className={styles.card}>
<h2>Documentation &rarr;</h2>
<p>Find in-depth information about Next.js features and API.</p>
</a>

<a href="https://nextjs.org/learn" className={styles.card}>
<h2>Learn &rarr;</h2>
<p>Learn about Next.js in an interactive course with quizzes!</p>
</a>

<a
href="https://github.com/vercel/next.js/tree/canary/examples"
className={styles.card}
>
<h2>Examples &rarr;</h2>
<p>Discover and deploy boilerplate example Next.js projects.</p>
</a>

<a
href="https://vercel.com/new?utm_source=create-next-app&utm_medium=default-template&utm_campaign=create-next-app"
className={styles.card}
>
<h2>Deploy &rarr;</h2>
<p>
Instantly deploy your Next.js site to a public URL with Vercel.
</p>
</a>

<Link href="/typescript">
<a className={styles.card}>
<h2>Our second page</h2>
<p>
Click here to go to the second page. The page where we'll
discover Typescript.
</p>
</a>
</Link>
</div>
</main>

<footer className={styles.footer}>
<a
href="https://vercel.com?utm_source=create-next-app&utm_medium=default-template&utm_campaign=create-next-app"
target="_blank"
rel="noopener noreferrer"
>
Powered by{" "}
<span className={styles.logo}>
{/* There's another important thing to mention here. Instead of <img>, in Next.js we'll need to use their <Image> component.
We need this because Next.js made many improvements on the <img> tag from HTML and put it in their own component.
It's much better! Check https://nextjs.org/docs/api-reference/next/image if you want to know why... */}
<Image src="/vercel.svg" alt="Vercel Logo" width={72} height={16} />
</span>
</a>
</footer>
</div>
);
};

// here, the newly created Home component is being exported so other files can find it.

export default Home;

Just copy paste it and see what happens... You can then create a new file called typescript.tsx and put it in your /pages folder. Paste the following in there, but don't execute it yet. Try to understand what it does first.

import type { NextPage } from "next";

const TypescriptScreen: NextPage = () => {
//primitive types, string literals, operators, comparisons, typeof and creating your own types

/*
This is how you declare variables. Variables can be constant, or they can be flexible.
*/
const numberA = 1; // To declare a constant value we use "const". We are declaring a number here.
let numberB = 2; // To declare a variable we later want to change, we can use "let". Again, we are declaring a number.

const sum = numberA + numberB; // what is the result?
/*
+ is called arithmetic operator.
You can also use other ones... arithmetic operators:
- (subtraction)
* (multiplication)
/ (division)
% (modulus)
++ (increment)
-- (decrement)
*/

const typedSum: number = numberA + numberB;
// here we have done the exact same as above,
// only we have specifically told the compiler that the variable must be a number.
// you can always do that in typescript if you want to be more explicit,
// but most of the time, it's inferred automatically for you. Typescript 'just knows' ;)

// usually, you're never that explicit... but I want to explalin these primitives to you.
// The primitive types that typescript offers
// we have the following types by default in typescript:
// string, number, boolean, null, undefined, any, void, array, object

//these are two ways to create strings.
const text: string = "The result is"; //normal string
const text2: string = `The result is ${sum}... ok?`; //template string (using backticks) can also include variables.

const isLoaded: boolean = true; // booleans can be true or false

const nothing: null = null; // this can only be null
const alsoNothing: undefined = undefined; // this can only be undefined.
//what's the difference?

const something: any = "hmmm"; // any can hold any value.

const returnNothing = (): void => {}; //here, I've created a function that returns nothing. It returns void

const sampleArray = [text, text2];
//can you guess the type of this?
//right, it's a string[], a string array. It can also be written like this: Array<string>

// This is how you create objects. Objects have keys and values.
// Keys are mostly strings, and values can be anything!
const textsObject = {
text,
text2,
};

/*
below you can find three ways to log something.
console.log is a function that takes any amount of arguments.
These arguments can have any value.
Those values will then be printed to your debugger
*/
console.log("The result is", sum); // here we give the console.log function two arguments.
console.log(text2); // here we give the console.log function one argument. It's
console.log({ sum });

return (
<div>
Let's learn typescript!
<div>
<p>
{numberA} + {numberB} = {sum}
</p>
</div>
</div>
);
};

export default TypescriptScreen;

/**
* All right!
*
* There's a lot happening. Have you read it?
* Then save this, and try to go to this page by clicking the link on the homepage.
*
* Have a look what it does, and then go back to the course.
*/

Comparisons

Typeof

Props

differences from html

events

useState

useEffect

Did you learn something?

Click the button below to tweet about what you thought of this section, what you've made, what you learned... Also don't forget to share it with us via slack! Cool tweets (or other social media posts) will be selected and presented on this page!

Tweet!