Learn React.js in 30 Minutes (Crash Course 2019)

As a programmer or blockchain developer you can’t continue putting off learning React.js since it’s one of the most effective tools to create powerful web applications and dApps. In this fast paced guide you’ll learn to become proficient with React.js from the beginning, step-by-step even if you’re never used it before.

This guide is for you if you have experience with React as a quick update to the latest changes in 2019 - 2020 where most of the components are functions with hooks. Read on.

Here’s what you’ll learn:

  1. Learn to setup webpack
  2. Learn to create react files
  3. Setup package.json scripts
  4. Setup a static express server in node.js
  5. Updating state, using effect and importing files
  6. Conclusion

Here’s the video version so that you learn it in 30 minutes and see the entire process in case you get stuck or if you prefer video. Made by myself:

1. Learn to setup webpack

Let’s get straight to it. To use React.js we need webpack which is a tool that converts our modern javacript ES6 code into something that browsers can understand. ES6 is a javascript version that is still in development but it is used by most modern web applications since it’s quite stable and gives you access to many new functions that are essential for react.

Go ahead and create a new folder where you’ll project files will go in your desktop. Call it react-starter then open your command line utility and move inside that folder. You need to have node.js installed to proceed, if you don’t have it download it at nodejs.org since it’s a free open source software. After that, execute these commands in order in your terminal, command line or powershell:

1
npm init -y
1
npm i -g yarn
1
yarn add --dev @babel/core @babel/polyfill @babel/preset-react @babel/preset-env babel-loader style-loader css-loader html-webpack-plugin react react-dom webpack webpack-cli
1
yarn add express body-parser

Here’s a brief explanation of those commands:

  1. The npm init allows you to start a node.js project in that directory which allows you to install npm (node package manager) dependencies, required to download and use webpack and react among many other tools.
  2. The npm i -g yarn simply installs the utility yarn which is a faster alternative to npm as a package manager meaning you’ll be able to download and process dependencies faster.
  3. The next line is installing all the dependencies we need for configuring our project. You see react there, webpack, babel and many presets. Those are for converting javacript files into code understandable by browsers which means they allow you to use modern javascript.
  4. The last line is to install the required dependencies for creating a static server that sends the files when accesing your page.

Next, create the folders dist and src at the root of your project. Dist is the distribution folder which is the one sent to the browsers when they access your page and src is the source folder where all the code is located.

After that, create a file at the root of your folder named webpack.config.js the naming is important so make sure to get it right. That’s the webpack configuration where we’ll tell it how we want it to process our files. Copy manually the following code inside that file:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
const HTMLPlugin = require('html-webpack-plugin')
const { join } = require('path')
module.exports = {
entry: [
'@babel/polyfill',
join(__dirname, 'src', 'App.js'),
],
output: {
path: join(__dirname, 'dist'),
filename: 'build.js',
},
module: {
rules: [{
loader: 'babel-loader',
test: /\.js$/,
exclude: /node_modules/,
query: {
presets: ['@babel/preset-env', '@babel/preset-react'],
}
}, {
test: /\.css$/,
exclude: /node_modules/,
use: ['style-loader', 'css-loader'],
}]
},
plugins: [
new HTMLPlugin({
title: 'My React application',
template: join(__dirname, 'src', 'index.ejs'),
hash: true,
})
]
}

That webpack configuration allows you to start by going into the src/App.js file and then going from there until all the files have been converted to output them into the dist folder.

Now create a file named index.ejs inside your src/ directory with the following code:

1
2
3
4
5
6
7
8
9
10
11
12
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<title><%= htmlWebpackPlugin.options.title %></title>
</head>
<body>
<div id="root"></div>
</body>
</html>

The extension .ejs indicates that we are using the node.js templating engine ejs which is used to include variables inside html files. As you can see the only thing different from normal html is the webpack plugins block which is a variable coming from the webpack config, particularly from the html-webpack-plugin dependency used to clean the cache everytime you build your files with webpack so that you see the new changes everytime you reload your browser.

The real reason is a bit more confusing so be sure to search more about that package on the internet if you are curious.

2. Learn to create react files

React files have a special syntax where we incorporate HTML valid code inside javascript files. That’s impossible with normal javascript but because we’re using something called JSX, we can do so. It’s a virtual representation of the web page in your files. Don’t worry if you don’t get it, it will be clearer over time how it all ties together.

So go ahead and create an App.js file inside your source folder. Notice how the first letter is uppercase to indicate that the file is a React component, an element that you can use inside other components. Think of it as a chunk of HTML code that you can insert wherever you want.

Inside your App.js type this code manually, don’t copy paste it because when you write it with your own hands is when you actually develop that muscle memory to learn faster:

1
2
3
4
5
6
7
8
import React from 'react'
import { render } from 'react-dom'
function App () {
return (
<div>The app has been setup</div>
)
}
render(<App />, document.querySelector('#root'))

What we’re doing there is import react and react-dom which is a utility to render your react components into your HTML code. The function App() is a react functional component which is the new modern way of creating components. Previously we had class based components, even though they are still perfectly valid they are not used as much compared to functional components.

3. Setup package.json scripts

The package.json file is extremely important since it contains essential configuration about your overall project. There are all the dependencies used in the project so that others can install the same required tools to run the same code without issues.

Go ahead and open it. You’ll see a "scripts" section which contains your own customized utilities to execute smaller programs such as webpack to convert your files into the right build.

So remove the "test" line inside your "scripts" section and instead write the following scripts:

1
2
3
4
5
"scripts": {
"watch": "webpack -dw",
"compile": "webpack -p",
"start": "node server.js"
},

That will allow you to execute yarn run watch, yarn run compile and yarn run start, commands that we’ll need to convert the modern javascript files and to spin up a static server.

4. Setup a static express server in node.js

To be able to use our application locally, we need a static server. Its whole purpose is to send the requested files to the user whenever he enters your domain or to see your app locally.

Go ahead and create a server.js file in your at the root of your project directory and type the following code to create the server:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
const express = require('express')
const bodyParser = require('body-parser')
const { join } = require('path')
const app = express()
const port = 8000
app.use(bodyParser.json())
app.use(bodyParser.urlencoded({extended: true}))
app.use((req, res, next) => {
// Logger
let time = new Date()
console.log(`${req.method} to ${req.originalUrl} at ${time.getHours()}:${time.getMinutes()}}`)
next()
})
app.use(express.static('dist'))
app.listen(port, '0.0.0.0', (req, res) => {
console.log('The server has been started')
})

There we are using express as the web server framework for accepting and managing requests in node.js. Then we create a logger that shows us who is requesting what url and when. Finally we are using express.static('dist') to allow users to freely access all the files located inside the distribution folder. If you’re curious about the exact details, check the express.js docs to understand how it works.

5. Updating state, using effect and importing files

Now that we have all of the files properly setup, we can begin creating React code! Trust me that it gets easier over time once you understand the purpose of each tool and how to set it up again.

We’ll create a simple React application just to understand how it works that allows users to write text in an input and see the resulting value right below in real-time using what’s called the react state, special variables that update your view as you change your values.

Start by creating a components/ folder inside your src/ since we need a place to store all of our components except for that initial App.js. Then, inside components/ create a file called InputBox.js. Add the following code to the InputBox component file, I’ll explain it right below:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
import React, { useState, useEffect } from 'react'

export default ({ props }) => {
const [value, setValue] = useState('')
useEffect(() => {
setValue('Empty')
}, [])
return (
<div className="input-box">
<input
type="text"
value={value}
onChange={e => {
setValue(e.target.value)
}}
/>
<p>Your input is: {value}</p>
</div>
)
}

Here’s the breakdown:

  1. As you can see we’re importing the functions useState and useEffect from the react package. Those are known as react hooks which is a special type of function that gets detects when something changes in your component and updates the visual design in real-time.
  2. Then we create and export at the same time an anonymous arrow function that contains a value state variable and a general useEffect hook.
  3. The useState variable returns 2 elements: The first one is the “smart” variable that you want with whatever name you choose and the second one is a function that updates that smart variable so that react knows when something happens in the interface and the content inside useState('') is the initial value of the value variable, in this case an empty string.
  4. Then we define a useEffect function that simply updates our value state variable with the value Empty as an example. We don’t necessarily need that, but just for demonstration purposes I’ve added it. The second parameter of the useEffect hook is an array. If that array is empty just like in this case, then the hook will be executed only once, when the page loads. If there’s a variable name for instance: [value], then the function inside the useEffect hook will be executed whenever the value variable changes so that you can execute other logic.
  5. Finally we have the return value which simply returns a div with an input and a text. Notice how the input has a onChange event which is a special react event that gets executed whenever the input of the input changes. Inside that function we’re simply updating the value variable to update its value so that you can see what you’re typing down below, inside here: <p>Your input is: {value}</p>

6. Conclusion

This has been a short article that I created as an introduction to those interested in React development as a quick summary of the core things you need to know. The setup process is laborious but it makes perfect sense once you do it multiple times. React on itself is a completely different javacript than the one you may be used to.

However React is here to stay and it has proven across literally millions of projects that it is capable of creating extremely efficient and stable User Interfaces that are easy to manage, maintain and scale compared to traditional javascript frontends. If you want to learn more about react and are serious when it comes to earning money online, check my new course heatoon.com which is now available.

If you liked this article, be sure to share it with your friends and comment down below what you think can be improved for the next series of informational guides. Also join the email list so that you can receive new updates with interesting and valuable articles that will make you a better and richer developer

Join hundreds of developers like you

Receive monthly quality content that makes you a better Blockchain and Fullstack Web Developer straight to your email. No spam, all pure value. Because a community is the best way to learn.