React Tutorial for Beginners

Oct. 12, 2020, 5:16 p.m.

JavaScript React · 14 min read

React Tutorial for Beginners

Last Modified: Oct. 14, 2020, 12:39 p.m.

What is React?

React, also known as React.js or ReactJS, is an open-source front-end JavaScript library maintained by Facebook.

 

How is React used?

React allows developers to quickly create reusable user interface (UI) components for mobile or single-page applications. 

 

What can you build with React?

Social media, e-commerce, and productivity apps can all be made in React, along with many other UI components.

For this React tutorial, we will cover the installation process, basic file structure, and DOM rendering.

 

What is required to use React.js?

React, similar to any other web framework, needs certain locally installed packages to work correctly.

To follow this React tutorial, you need to:

  • install Node.js
  • install npm
  • install and configure create-react-app

 

You do not need any prior experience with React to follow the React tutorial below. 

 


 

Node.js

What is Node.js?

Node.js is a backend framework that makes JavaScript a server-side language, executable outside of the web browser.

 

Why is Node.js used with React.js?

Developers use Node.js and React.js together to create the front and backend of an app. Node.js handles the data storage while React loads in the UI components in the frontend.

You do not need Node.js to use React, but it is helpful to use Node.js and React together.

 


 

npm

What is npm?

npm is a package manager for JavaScript, similar to how pip is the package manager for Python.

 

Why is npm used with React.js?

The package manager npm allows developers to run React scripts that open the app in a browser, compile the code, and deploy. 

It also helps install node programs via the command prompt and manages dependency conflicts. 

 


 

Install Node.js and npm

Node.js and npm are installed together with the Node installer

 

Install Node on Windows:

nodejs.org/en/download/ - Windows Installation

Node.js Windows Install

Select "Window Installer" and download the file to your computer. 

Wait for the file to finish downloading, then click on the file to open the "Node.js Setup Wizard". 

Complete the entire "Node.js Setup Wizard" installation process. 

 

Install Node on macOS:

nodejs.org/en/download/ - macOS Installation

Nodejs macOS install

Select "macOS Installer" and wait for the file to download.

Once the download completes, open the file in your Finder. 

Complete the entire "Install Node.js" installation process.

 

Check Node.js and npm are installed:

Check version number - Windows Command Prompt

C:\Users\Owner>node -v
v12.13.1

C:\Users\Owner>npm -v
6.12.1

 

Check version number - macOS Terminal

User-Macbook:~ user$ node -v
v12.13.1

User-Macbook:~ user$ npm -v
6.12.1

Once the install is complete, the easiest way to confirm the installation is to check the version number.

Type node -v in your Command Prompt or Terminal and a version number should appear.

Also, run npm -v to make sure npm is installed correctly. 

 


 

Create a React App

Facebook offers an open-source create-react-app that comes with pre-configured files and packages.

This includes a live development server, the automatic compilation of CSS, JSX, and React files, and ESLint to alert the developer to mistakes in the code. 

We'll be installing the create-react-app directory using the CLI.

 

Make a folder for your React projects:

But first, let's create a directory to hold the React chatbot project and any future React apps. 

 

Create a react directory - Windows Command Prompt

C:\Users\Owner>cd desktop

C:\Users\Owner\desktop>mkdir react

C:\Users\Owner\desktop>cd react

C:\Users\Owner\desktop\react>

 

Create a react directory - macOS Terminal

User-Macbook:~ user$ cd desktop

User-Macbook:desktop user$ mkdir react

User-Macbook:desktop user$ cd react

User-Macbook:react user$

Enter into the directory of your choosing. 

Then create a new directory for your React projects using the command mkdir.

In this case, the directory is called react, located in the Desktop directory.

Be sure to cd into the new directory react before moving on.

 

 

Create the app using Facebook's create-react-app

create-react-app - Windows Command Prompt

C:\Users\Owner\desktop\react> npx create-react-app react-example

 

create-react-app - macOS Terminal

User-Macbook:react user$ npx create-react-app react-example

Now it's time to create your actual React app.

Run the command npx create-react-app followed by the name of your project.

The command ran above is npx create-react-app react-example.

A react app named react-example and packages react, react-dom, and react-scripts with cra-template will be installed.

This will take a few minutes. In the meantime, get up and stretch your legs. 

 

Success message

Command Prompt/Terminal after successful React app creation

...

Created git commit.

Success! Created react-example
Inside that directory, you can run several commands:

  npm start
    Starts the development server.

  npm run build
    Bundles the app into static files for production.

  npm test
    Starts the test runner.

  npm run eject
    Removes this tool and copies build dependencies, configuration files
    and scripts into the app directory. If you do this, you can’t go back!

We suggest that you begin by typing:

  cd react-example
  npm start

Happy hacking!

When your app is done being created, you will get the success message listed above. This means it's time to open your React app in a browser window.

 


 

Open your React app in the browser

Run app - Windows Command Prompt

C:\Users\Owner\desktop\react> cd react-example

C:\Users\Owner\desktop\react\react-example> npm start

 

Run app - macOS Terminal

User-Macbook:react user$ cd react-example

User-Macbook:react-example user$ npm start

cd into the project with the command cd react-example

Then run the command npm start to open your React app in the browser. 

 

React app in the browser

React Successful Install

The development server will start and a new browser window will open with the message "Edit src/App.js and save to reload".

 


 

Open your React app in a text editor

To edit your React files, you need a text editor such as Sublime, Notepad++, or Visual Studio Code. 

For this tutorial, we will use Sublime Text

 

react-example project in Sublime 

React App in Sublime Text

Open your project in Sublime text.

You should open the project directory react-example to see the folders and files just created using the command create-react-app

The project contains a node_modulespublic, and src folder along with .gitignorepackage-lock.jsonpackage.json, and READ.md files.

 


 

Understanding the files in your React App

The main files we'll use are in the src directory.

But first, let's go to the package.json file to see the React scripts ran using npm.

 

packages.json

react-example > package.json

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

The command npm start runs the script react-scrips start, the script that runs the development server.

 

public > index.html

react-example > public > index.html

<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="utf-8" />
    <link rel="icon" href="%PUBLIC_URL%/favicon.ico" />
    <meta name="viewport" content="width=device-width, initial-scale=1" />
    <meta name="theme-color" content="#000000" />
    <meta
      name="description"
      content="Web site created using create-react-app"
    />
    <link rel="apple-touch-icon" href="%PUBLIC_URL%/logo192.png" />
    <!--
      manifest.json provides metadata used when your web app is installed on a
      user's mobile device or desktop. See https://developers.google.com/web/fundamentals/web-app-manifest/
    -->
    <link rel="manifest" href="%PUBLIC_URL%/manifest.json" />
    <!--
      Notice the use of %PUBLIC_URL% in the tags above.
      It will be replaced with the URL of the `public` folder during the build.
      Only files inside the `public` folder can be referenced from the HTML.

      Unlike "/favicon.ico" or "favicon.ico", "%PUBLIC_URL%/favicon.ico" will
      work correctly both with client-side routing and a non-root public URL.
      Learn how to configure a non-root public URL by running `npm run build`.
    -->
    <title>React App</title>
  </head>
  <body>
    <noscript>You need to enable JavaScript to run this app.</noscript>
    <div id="root"></div>
    <!--
      This HTML file is a template.
      If you open it directly in the browser, you will see an empty page.

      You can add webfonts, meta tags, or analytics to this file.
      The build step will place the bundled scripts into the <body> tag.

      To begin the development, run `npm start` or `yarn start`.
      To create a production bundle, use `npm run build` or `yarn build`.
    -->
  </body>
</html>

The file index.html only contains meta tags and a <div id="root"></div>. This id is what places our React app in the index.html

 

src > index.js

react-example > src > index.js

import React from 'react';
import ReactDOM from 'react-dom';
import './index.css';
import App from './App';
import * as serviceWorker from './serviceWorker';

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

// If you want your app to work offline and load faster, you can change
// unregister() to register() below. Note this comes with some pitfalls.
// Learn more about service workers: https://bit.ly/CRA-PWA
serviceWorker.unregister();

Open the file index.js. You should see the information listed above. Think of this file as the central JavaScript file of the app.

index.js renders the React component from App.js in the HTML document index.html

 

src > App.js

react-example > src >App.js

import React from 'react';
import logo from './logo.svg';
import './App.css';

function App() {
  return (
    <div className="App">
      <header className="App-header">
        <img src={logo} className="App-logo" alt="logo" />
        <p>
          Edit <code>src/App.js</code> and save to reload.
        </p>
        <a
          className="App-link"
          href="https://reactjs.org"
          target="_blank"
          rel="noopener noreferrer"
        >
          Learn React
        </a>
      </header>
    </div>
  );
}

export default App;

Open the file App.js. You should see the code listed above.

This information is the code that was rendered in the browser when we ran npm start.

 

The remaining files will not be used in this tutorial.

 


 

Create a class component

src

react-chatbot > src

Delete all of the files in the src folder except for the index.js and App.js files. index.js and Apps.js are the main files we will use to render a React class component.

 

We will start with index.js and App.js slowly growing our project's file structure from there. 

 

index.js (updated)

react-example > src >index.js (updated)

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


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

As stated earlier, the index.js is the connecting file between your React App file, App.js, and the index.html file.

React, ReactDOM, and the component App from src > App.js are imported at the top of the file. 

React creates the UI components stored in the App.js file which, in turn, are rendered in the browser by the ReactDOM.render() function. 

The function takes in two arguments -- the HTML/JSX code from the App.js component and an HTML element from index.html.

 

App.js (updated)

react-example > src > App.js (updated)

import React, { Component } from 'react';

class App extends Component {

       
}

React apps use components -- JavaScript classes or functions used as building blocks to accept properties and return the React element's code.

App.js imports React and {Component} at the top of the file. 

Then a React component can be written below. 

Let's add the class component called App that uses the extend Component statement. Please note that the React component's name is always uppercase and must include the extends Component statement.

{ Component } is loaded in as a property of React at the top of the file so we can call extends Component rather than extends React.Component

The extends Component statement gives your component access to the React Component's methods. The React Component methods include:

  • render()
  • constructor()
  • componentDidMount()
  • componentDidUpdate()
  • componentWillUnmount()

 

react-example > src > App.js

import React, { Component } from 'react';

class App extends Component {
  render() {
    return (
      <div className="App">
        
        <h1>Hello World!</h1>
        <p>This is my first React App.</p>
        
      </div>
    );
  }
       
}

Then render a division element within the return. Every React component requires a render() method. 

You should notice this is not an HTML code. It is actually JavaScript XML, commonly referred to as JSX, a markup language that organizes and stores data.

Written similarly to HTML, most JSX elements are formatted like HTML elements. However, there are a few key differences:

  1. JSX uses className instead of the HTML attribute class (i.e. ClassName="App")
  2. camelCased values call methods and properties (i.e. onClick())
  3. Slashes go at the end of self-closing tags (i.e. <img />)
  4. Inline style attribute values are placed in curve brackets (i.e. style={{color: "red"}})
  5. Style properties with two names are camelCased (i.e. style={{backgroundColor: "blue"}}
  6. JavaScript expressions including functions, variables, and properties are embedded inside JSX using curly brackets (i.e. { name }). 

Everything else in the return() method is written in plain HTML. 

 

react-example > src > App.js

import React, { Component } from 'react';

class App extends Component {
  render() {
    return (
      <div className="App">
        
        <h1>Hello World!</h1>
        <p>This is my first React App.</p>
        
      </div>
    );
  }
       
}

export default App;

The last piece of code exports the component App so it can be imported in the index.js file. 

 

View the App component in the browser

React with your own components

Facebook's create-react-app environment has an auto-reload feature.

You do not need to refresh the page to view the updates made to your files. 

Go to the browser tab with your local development server, http://localhost:3000/, and you should see the page shown above.

 


 

React file structure - separating React components

You can choose to add as many React components as you wish to a React App. However, it is always a good idea to divide your components so they can more easily be added and edited.

 

Create a new file

react-example > src > (New Folder) components > (New File) Welome.js

import React, { Component } from 'react';

class Welcome extends Component {
  render() {
    return (
      <div className="Welcome">
        
        <h1>Hello World!</h1>
        <p>This is my first React App.</p>
        
      </div>
    );
  }
       
}

export default Welcome;

Create a new folder called components in the src file.

Within this new folder, create a file called Welcome.js.

This file will hold the welcome text we just added. Just be sure to change the component App to Welcome

 

App.js (updated)

react-example > src > App.js (updated)

import React, { Component } from 'react';
import Welcome from "./components/Welcome";


class App extends Component {
  render() {
    return (
      <div>
        
        <Welcome />
        
      </div>
    );
  }
       
}

export default App;

Now we can return to the App.js file and import our new component Welcome from Welcome.js at the top of the file. 

Then we can go inside the class App and return the Welcome component using the JSX format <Welcome />. This is the format used to refer to components inside other components. 

If you look back at your development server in the browser, the app should still look the same. 

 


 

React Developer Tools

React App in Developer Tools

React components cannot be inspected in the browser Developer Tools. The components render in HTML.

 

To see the React Components, you can install React DevTools for Chrome. This is an extension offered by Facebook that adds React debugging tools to Chrome Developer Tools and allows the inspection of React components hierarchies. 

 

React App seen in Developer Tools with Facebook's React Chrome Extension

Two tabs will be added to your Chrome DevTools -- Components and Profiler. 

 


 

Solving errors in React

Facebook added the tool ESLinit pre-built into the create-react-app environment to help identify and report any bugs or errors in the JavaScript code.

React Error page

The error pages provide the file name, the exact line number of the error, followed by an error message explaining the cause.

 

Command Prompt/Terminal

Failed to compile.

./src/App.js
  Line 8:7:   'React' must be in scope when using JSX  react/react-in-jsx-scope
  Line 10:9:  'React' must be in scope when using JSX  react/react-in-jsx-scope

Search for the keywords to learn more about each error.

The same error is also found in the Terminal or Command Prompt.

 

 

React Console Error

Errors can also be found in the Developer Tool Console with a similar error report

 

ERROR: Failed to Compile. 'React' must be in scope when using JSX

If you forget to import React:

./src/index.js
  Line 6:17:  'React' must be in scope when using JSX  react/react-in-jsx-scope

Search for the keywords to learn more about each error.

Solution:

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


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

Be sure to import React at the top of the file. 

 

ERROR: Failed to Compile. 'Component' is not defined

If you forget to import Component:

./src/components/Welcome.js
  Line 3:23:  'Component' is not defined  no-undef

Search for the keywords to learn more about each error.

Solution:

import React, { Component } from 'react';

class Welcome extends Component {
  ...
       
}

export default Welcome;

Import Component at the top of the page. 

 

ERROR: Failed to Compile. Parsing error

If you forget to add curve brackets to Component:

./src/components/Welcome.js
  Line 1:15:  Parsing error: Unexpected token, expected "{"

> 1 | import React, Component from 'react';
    |               ^

Solution:

import React, { Component } from 'react';

class Welcome extends Component {
  ...
       
}

export default Welcome;

Make sure { Component } is imported at the top of the page.

 

ERROR: Failed to Compile. Attempted import error

If you forget to export the App:

./src/index.js
Attempted import error: './App' does not contain a default export (imported as 'App').

Solution:

import React, { Component } from 'react';
import Welcome from "./components/Welcome";


class App extends Component {
  render() {
    return (
      <div>
        
        <Welcome />
        
      </div>
    );
  }
       
}

export default App;

Be sure to export the created component at the bottom of the file. 

 

Blank page - CONSOLE ERROR: 'Welcome' is defined but never used

If you are not getting an ESLinit error but the page is still blank:

react_devtools_backend.js:2273 ./src/App.js
  Line 2:8:  'Welcome' is defined but never used  no-unused-vars

If you are getting a blank page, be sure to check the Development Tools console. Often there is a warning listed. In the case above, the warning is appearing because the Welcome component is not defined in the component App. 

Solution:

import React, { Component } from 'react';
import Welcome from "./components/Welcome";


class App extends Component {
  render() {
    return (
      <div>
        
        <Welcome />
        
      </div>
    );
  }
       
}

export default App;

Make sure the component is added to the return function. 

 

ERROR: Target container is not a DOM element

React error if you delete or rename the HTML id

 

Uncaught Error: Target container is not a DOM element.

The error above occurs if you delete the HTML id in index.html or rename it in the index.js file.

Solution 1:

...

<body>
    <noscript>You need to enable JavaScript to run this app.</noscript>
    <div id="root"></div>
</body>

See that <div id="root"></div> is still in the public > index.html file. 

Solution 2:

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


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

Check that the ReactDOM render function calls the same id listed in the HTML template.

 


 

Stop the React development server

Command Prompt/Terminal

(Ctrl + C or Command + C)

Terminate batch job (Y/N)? y

Stop running the development server by using the command CTRL + C or command + C in the command prompt. 

The prompt will then ask: Terminate batch job(Y/N)?

Type y for yes, terminating the batch job and quitting the server. Your prompt will then appear.


0
Subscribe now

Subscribe to stay current on our latest articles and promos





Post a Comment
Join the community

0 Comments