DEV Community

loading...

Creating a React App - Explained

aravsanj profile image Aravind Sanjeev ・10 min read

Alt Text

I know what you're thinking. This is a dev community, people here already know how to create a React app. If you're coming from YT, then you already know the easiest way to create a React app is by using the create-react-app environment. Besides, there is already a million tutorial on how to create a React app. But what people often miss in these tutorials is the concept-level thinking that goes into making them.

In my last post, I have written how a React works by underlying the difference between React and plain JS programming.

In this piece, I wish to write about creating a React app the way you'll understand what's going on. This is not necessary. Using the popular method of create-react-app is more than enough to kick start your application development. But understanding how we got there will help you once you start digging deeper into React.

If you didn't understand something I wrote here, chances are you didn't read my last post.

From our last post, I wrote that React is simply a JS library. And a JS library is a bunch of prewritten JS codes.

That means, it is technically possible to use React in a normal JS program. All you have to do is reference the library.

<script src="https://unpkg.com/react@17/umd/react.production.min.js"></script>
<script src="https://unpkg.com/react-dom@17/umd/react-dom.production.min.js"></script>
Enter fullscreen mode Exit fullscreen mode

So while writing a normal JS application, you can use React functions by just adding the above code. The link contains a production-ready React version. For development, use the development version available here.

Now when you use React functions, make sure to use them in between the tags.

<script type="text/babel">
--React codes here --
</script>
Enter fullscreen mode Exit fullscreen mode

What? Why?

When you're normally writing JavaScript, you write them in between these two tags.

<script type="text/javascript">
--Normal JS--
</script>
Enter fullscreen mode Exit fullscreen mode

But for React, you use text/babel instead of text/javascript. As I already told you in my previous post, React components actually outputs JSX. Browsers do not directly implement JSX output but instead depends on the compiler babel. React library is built on ES6 syntax. To convert ES6 syntax to regular JS, you need the babel compiler. Now, if you wrote it without using any ES6 features then feel free to use the old tag itself. But, you avoid all the goodies that come with ES6.

For a small recap:

  • React is a library.
  • That means you can use React in normal JS by referencing it.
  • React is built on ES6 syntax.
  • Therefore a compiler called babel is required to convert it into regular JS syntax.
  • Hence you write React codes in script tags with type = text/babel.

If you still didn't get where the babel came from, feel free to look up and learn ES6 which is a prerequisite for learning React.

Although this one way of using React library, this is not THE way of creating a react application. For that, let's first go through some simple definitions.

Package

We know already what is JS library. A package is a bunch of such libraries that are grouped [packaged] together. But it is not necessary that everything inside a package has to be libraries. It can be anything that is grouped together as long as the individual units have some functional ability. So what's inside a package are termed modules.

Package manager

A package manager is a piece of software that is used to manage packages. Typically, it should be able to install and uninstall the modules we want.

Node Packet Manager (NPM) and Yarn are two popular package managers out there.

Now you know that React is a library and it is possibly contained inside a package and you need a package manager to access and install it.

NodeJS

NodeJS is a runtime environment for back-end development. But as far as we are concerned, we need to download NodeJS since it comes with the Node package which among many other things, has our React library.

It also comes bundled with Node Package Manager (NPM), which helps us install this library (and many others) we can use.

Now from this point, I actually want you to do what I write. Assuming that you already installed NodeJS, open your command prompt in windows.

Initially, the screen will be like this:

c:\users\YourUserName>
Enter fullscreen mode Exit fullscreen mode

If you want, you can change your directory. But this for just learning purposes, you can delete it later.

Now do this:

c:\users\YourUserName>mkdir YourAppName
Enter fullscreen mode Exit fullscreen mode

mkdir stands for "Make Directory". Once you run it, a folder named YourAppName will be created. Now your screen will look like this:

c:\users\YourUserName>mkdir YourAppName
c:\users\YourUserName>
Enter fullscreen mode Exit fullscreen mode

Access the now created YourAppName folder using:

c:\users\YourUserName>cd YourAppName
Enter fullscreen mode Exit fullscreen mode

Running this will change the current directory to the folder YourAppName. Now, this what you see on the screen:

c:\users\YourUserName>mkdir YourAppName
c:\users\YourUserName>cd YourAppName
c:\users\YourUserName\YourAppName>
Enter fullscreen mode Exit fullscreen mode

You're now inside the YourAppName folder. Now it is time to initialize the project. Initializing the project will create the package.json file.

To initialize, run:

c:\users\YourUserName\YourAppName>npm init -y
Enter fullscreen mode Exit fullscreen mode

Here the init stands for initialize and -y just stands for yes.

After running, your screen output will look something like this:

Wrote to C:\Users\Aravind\react\package.json:

{
  "name": "react",
  "version": "1.0.0",
  "description": "",
  "main": "index.js",
  "scripts": {
    "test": "echo \"Error: no test specified\" && exit 1"
  },
  "keywords": [],
  "author": "",
  "license": "ISC"
}

Enter fullscreen mode Exit fullscreen mode

You have successfully created a package.json file in the YourAppName folder. Feel free to open package.json using notepad and see what has been written, which is the same that is been displayed on the screen.

package.json is a file that holds metadata of the program, like author name, license, version, etc. But there is more to the package.json file as we will see below.

Now let's install the react and react-dom libraries.

npm install react
npm install react-dom
Enter fullscreen mode Exit fullscreen mode

Here we successfully installed both the react and react-dom libraries. If you now visit your YourAppName folder, you will see a new folder, and a file is created namely node_modules and package-lock.json. Inside node_modules folder are the react and react-dom libraries.

Now if you open the package.json file, you can see that the following has been added.

"dependencies": {
    "react": "^17.0.2",
    "react-dom": "^17.0.2",
  }
Enter fullscreen mode Exit fullscreen mode

Hence package.json also holds the dependencies of the app. When you install or uninstall something, it is automatically updated in the package.json file. This is very important because when someone installs our app using npm, this is used to pass the information on all the required dependencies which is then automatically installed without the user having to worry about it.

The package-lock.json file is also automatically updated when you do any modifications in the node_modules folder or in the package.json file. It is essentially kept in case you're collaborating with other developers.

Now, let's take a moment and go back to what I talked about in my previous post. I said the output of React is JSX. And I have mentioned above that the browser does not understand JSX and needs the babel compiler for conversion.

So when you're developing the app, you need the babel along with the rest of the modules for compiling purposes. You also need webpack, which essentially helps create/run the development server.

To install them, run the following.

npm install --save-dev @babel/core @babel/preset-env @babel/preset-react webpack webpack-cli webpack-dev-server babel-loader css-loader style-loader html-webpack-plugin
Enter fullscreen mode Exit fullscreen mode

Here the --save-dev flag is added to convey that these dependencies are being installed for development purposes.

Now once again, open the package.json file. You can see that the following has been added.

"devDependencies": {
    "@babel/core": "^7.13.14",
    "@babel/preset-env": "^7.13.12",
    "@babel/preset-react": "^7.13.13",
    "babel-loader": "^8.2.2",
    "css-loader": "^5.2.0",
    "html-webpack-plugin": "^5.3.1",
    "style-loader": "^2.0.0",
    "webpack": "^5.30.0",
    "webpack-cli": "^4.6.0",
    "webpack-dev-server": "^3.11.2"
  }
Enter fullscreen mode Exit fullscreen mode

Again we can see that all the installed modules are updated as dependencies in the package.json. But here, it is called devDependencies indicating that they're here for development.

Now browse to the YourAppName folder and create src and public folders. If you wish, you can use mkdir in the command prompt to do the same.

Inside the public folder, create the file index.html. Inside the src folder, create the files index.js, app.js, index.css & app.css.

It is not mandatory to follow this folder structure or file name. But this how typically an app is structured. index.js is automatically recognized as the main file. If you do consider changing this file name, make sure you change the main field in package.json accordingly.

If you're confused about how to make the files, just right click > New > Text Document and change the file name and extension.

Now open your index.html file using notepad and add the following.

<!DOCTYPE html>
    <head>

    </head>
    <body>
        <div id="root"></div>
    </body>
</html>
Enter fullscreen mode Exit fullscreen mode

This is just the typical blank HTML file we would receive from the server. We discussed this in detail in my last post.

Now fill out app.js

import React from 'react';

function App() {
  return (

    <div>Hello World!</div>

  );
}

export default App;
Enter fullscreen mode Exit fullscreen mode

We are just creating a minimal app that displays "Hello World" when run.

Notice that we have exported the app using export default App.

Now go to index.js and fill this.

import React from 'react';
import ReactDOM from 'react-dom';
import App from './App';

ReactDOM.render(
  <React.StrictMode>
    <App />
  </React.StrictMode>,
  document.getElementById('root')
);
Enter fullscreen mode Exit fullscreen mode

Here we have imported the App function and let it render using ReactDOM.render. I talked about this in detail in my previous post

Now we have all the three important files ready, that is index.html, index.js, & app.js.

We ignore having any CSS on our app, which for now is not necessary.

Now it is time to link all these three files so they can work in unison to run our React app.

For that, we will create a file called webpack.config.js in the YourAppName folder, which is the root folder.

Inside the webpack.config.js, we write.

var path = require('path');
var HtmlWebpackPlugin = require('html-webpack-plugin');

module.exports = {
    entry: './src/index.js',
    output: {
        path: path.resolve(__dirname, 'dist'),
        filename: 'index_bundle.js'
    },
    module: {
        rules: [
            { 
                test: /\.(js)$/, 
                use: 'babel-loader' 
            },
            { 
                test: /\.css$/, 
                use: ['style-loader', 'css-loader'] 
            }
        ]
    },
    mode: 'development',
    plugins: [

        new HtmlWebpackPlugin({
            template: 'public/index.html'
        })
    ]
}
Enter fullscreen mode Exit fullscreen mode

Essentially what we have done here is that we have set the entry point as index.js and the template as index.html. So when we are running the app, index.html will be first loaded to the browser as a template. App's entry point is index.js which will then render and load in the index.html.

If you look at the code of index.js, you can see that it renders <App /> which is the function in the app.js file and contains our entire react app. It is then returned in to the element <div id="root"></div>. Now we have successfully linked all three files for the proper execution of the app.

Again, it is explained in more detail in my previous post.

Now before we can run the app, we need to tell it to use babel for compiling. We also need to make keys for creating/starting the app.

For that, we head over to package.json.

Right below "main": "index.js", add

  "babel": {
    "presets": [
      "@babel/preset-env",
      "@babel/preset-react"
    ]
  },
Enter fullscreen mode Exit fullscreen mode

We also need to add scripts for npm run create and npm start commands.

So below "scripts": { add

"start": "webpack serve",
"create": "webpack,
Enter fullscreen mode Exit fullscreen mode

What we essentially did here is that when we run npm run create on the command prompt, it will start compiling using the webpack.

Then we can run npm start and it will start that server.

If you're using webpack < 4, replace webpack serve with webpack-dev-server --open.

Here is my complete package.json. If you're struggling with some syntax error, feel free to use VSCode to fix it.

{
  "name": "react",
  "version": "1.0.0",
  "description": "",
  "main": "index.js",
  "babel": {
    "presets": [
      "@babel/preset-env",
      "@babel/preset-react"
    ]
  },
  "scripts": {
    "start": "webpack serve",
    "test": "echo \"Error: no test specified\" && exit 1",
    "create": "webpack"
  },
  "keywords": [],
  "author": "",
  "license": "ISC",
  "dependencies": {
    "react": "^17.0.2",
    "react-dom": "^17.0.2",
  },
  "devDependencies": {
    "@babel/core": "^7.13.14",
    "@babel/preset-env": "^7.13.12",
    "@babel/preset-react": "^7.13.13",
    "babel-loader": "^8.2.2",
    "css-loader": "^5.2.0",
    "html-webpack-plugin": "^5.3.1",
    "style-loader": "^2.0.0",
    "webpack": "^5.30.0",
    "webpack-cli": "^4.6.0",
    "webpack-dev-server": "^3.11.2"
  }
}
Enter fullscreen mode Exit fullscreen mode

Now if you plan to share your repository, you should create a .gitignore file in the root folder.

Inside the .gitignore file, write.

# dependencies
/node_modules
/.pnp
.pnp.js

# testing
/coverage

# production
/build

# misc
.DS_Store
.env.local
.env.development.local
.env.test.local
.env.production.local

npm-debug.log*
yarn-debug.log*
yarn-error.log*
Enter fullscreen mode Exit fullscreen mode

This just keeps the unnecessary files from being shared. It is not needed to work but it is recommended and not using it could be counterproductive if you're sharing the work with multiple users.

Now run npm run create and then npm start. Here is my end result.

e

And finally, the easiest and most popular way to create a React app.

  1. Open the command prompt.
  2. Just run npx create-react-app app-name

A folder named app-name will be created with everything preinstalled and the basic app file/folder structure ready for use. In the end, you only need this. But now you know what each file does and how it all connects behind the scene. This knowledge, I hope, is going to help you at some point in your React journey. Peace.

Discussion (0)

pic
Editor guide