Creating a React application by hand

By default it’s probably better and certainly simpler to create a React application using yarn create but it’s always good to know how to create such an application from scratch yourself.

To start with, create a folder for our application and within it create a folder named src, within this create an empty file named index.tsx. Then add the following to this file

ReactDOM.render(
  <App />,
  document.getElementById('root')
);

We don’t actually have React dependencies available to our application at this point so run the following, these will add React as well as TypeScript and TypeScript definitions of React (obviously if you don’t want to work in TypeScript, remove the –typescript switches and the last three yarn commands).

yarn add react --typescript
yarn add react-dom --typescript
yarn add react-scripts
yarn add typescript
yarn add @types/react
yarn add @types/react-dom

yarn will create the package.json file and download the required dependencies. They purpose of the dependencies are probably pretty obvious – the first includes React, the second React-dom and the third gives us the scripts we’re used to when running the code generated React applications, such as supplying the script for yarn start.

Within the package.json add the following, which will add the scripts that we’re used to having available

"scripts": {
   "start": "react-scripts start",
   "build": "react-scripts build",
   "test": "react-scripts test",
   "eject": "react-scripts eject"
}

We’re going to need to also add a folder named public which we’ll place an index.html file in which will act as our default page. Here’s a minimal version copied from a React generated application

<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="utf-8" />
    <link rel="shortcut icon" href="%PUBLIC_URL%/favicon.ico" />
    <meta
      name="viewport"
      content="width=device-width, initial-scale=1, shrink-to-fit=no"
    />
    <meta name="theme-color" content="#000000" />
    <link rel="manifest" href="%PUBLIC_URL%/manifest.json" />
    <title>Game App</title>
  </head>
  <body>
    <noscript>You need to enable JavaScript to run this app.</noscript>
    <div id="root"></div>
  </body>
</html>

At this point we should be able to execute

yarn start

and now we should see a React application running in the browser.

If you want to add some CSS to the application, we can simply create index.css in the src folder, create your styles then to use it in index.tsx add the following at the top of the file

import './index.css';

If you’re using VSCode, as I am, you may wish to click on the status bar where it display a version of TypeScript, when index.tsx is open, and set to the most upto date version listed.