Richland College Multimedia Learning Center

JavaScript, React, and React
Home e-Handouts and Assignments Syllabus Resources Student Sites Other Classes RLC Multimedia
Updated 11/18/2020 at 9:10pm

React Introduction


References


What is React?

React is a JavaScript library that you can use to build web-based user interfaces and applications.

React was originally created by the developers at Facebook.

React runs in the Web browser as a library of Javascript objects. It creates a virtual DOM in the browser's memory and controls the browser's actual DOM from its in-memory objects. (The browser's DOM is its Document Object Model, and refers to the collection of objects in JavaScript which allow the JavaScript code to access and change the HTML page's tags/elements.)

React detects what has changed in the HTML page, and changes in the DOM only what needs to be updated. In this sense it is very efficient and fast.


Adding the React Library to your HTML Page

You can add React to your HTML page in one of two ways:

  1. Add the React code directly to the HTML page, or
  2. Set up a React programming environment on your computer, and add code to a JavaScript script page which manipulates an HTML page.

React Placed Directly in the HTML Page

Include 3 scripts in the <head> part of your HTML page. The first two scripts let us write React code in our JavaScript scripts; and the third, Babel, allows us to write JSX syntax and ES6 in older browsers. (We will see JSX and ES6 later in this handout.)

  1. <script src="https://unpkg.com/react@16/umd/react.production.min.js"></script>
  2. <script src="https://unpkg.com/react-dom@16/umd/react-dom.production.min.js"></script>
  3. <script src="https://unpkg.com/babel-standalone@6.15.0/babel.min.js"></script>

A sample page follows:

<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="UTF-8">
    <title>Sample React Page</title>
    <script src="https://unpkg.com/react@16/umd/react.production.min.js"></script>
    <script src="https://unpkg.com/react-dom@16/umd/react-dom.production.min.js"></script>
    <script src="https://unpkg.com/babel-standalone@6.15.0/babel.min.js"></script>
    </head>
  <body>
  
    <div id="mydiv"></div>

    <script type="text/babel">
      class Hello extends React.Component {
        render() {
          return <h1>Hello World!</h1>
        }
      }

      ReactDOM.render(<Hello />, document.getElementById('mydiv'))
    </script>
  </body>
</html>

If you save the previous code into an HTML page (for example, sample1.html), you can double-click the page in your local computer's file manager (Windows Explorer in Windows), and the browser should display "Hello World!" in the Web page.

Please note these points about the previous HTML page:


React Build Environment

You can also create a React "build" environment on your local computer, and pre-compile the React scripts.

The first steps in making a "build" environment involve your creating the create-react-app. Do these steps:

  1. Install Node.js on your computer.
    1. Open the official page for Node.js at Node.js Download Page. Make a note of where you download the installer.
    2. Run the installer that you downloaded.
  2. Upgrade npm on your computer: (It was probably installed by the previous steps.)
    1. On a Windows computer, open the cmd app. You can press <Window>+R (Run), type in cmd in the Search box, and press <Enter>.
    2. Type into the cmd Terminal window:
      npm install npm --global <Enter>
  3. Type into the cmd Terminal window:
    npm install -g create-react-app <Enter>
  4. Type into the cmd Terminal window:
    npx create-react-app myfirstreact <Enter>
    Please note that the previous command will create a directory called myfirstreact. It will be located here:
    C:\Users\<Username>\nodejs\myfirstreact
  5. Type into the cmd Terminal window:
    1. cd myfirstreact <Enter>
    2. npm start <Enter>

A new browser window will pop up with your newly created React App! If not, open your browser and type localhost:3000 in the address bar.


React ES6

ES6 stands for ECMAScript 6 and is the current version of JavaScript. Some people refer to it as ECMAScript 2015.

React uses ES6 syntax and features. You should know about the ES6 features and syntax anyway.

The main things that ES6 introduced into JavaScript are:


Classes

A class is used in JavaScript to create an object.

A class is a type of function, but instead of using the keyword function to define it, we use the keyword class, and the properties are assigned inside a constructor() method.

The constructor function (which is actually a method) is called automatically when the object is created and initiated.

A class can inherit properties and methods from another class. You use the extends keyword to inherit from another class.

React often requires you to create classes by inheriting from a React class.

The super() method refers to the parent class (the class from which your class inherits properties and methods).


Arrow Functions

Arrow functions allow us to write shorter function syntax.

Old syntax:

hello = function() {
  return "Hello World!";
}

New syntax:

hello = () => {
  return "Hello World!";
}

If the function has only one statement, and the statement returns a value, you can remove the brackets and the return keyword:

hello = () => "Hello World!";

If you have parameters, you put them inside the parentheses:

hello = (val) => "Hello " + val;

The this Keyword

The this keyword is handled differently in ES6.

In regular functions the this keyword represented the object that called the function, which could be the window, the document, a button, an input tag, or whatever.

With arrow functions, the this keyword always represents the object that defined the arrow function.


Variables

Variables in ES6 are quite different from previous versions of JavaScript.

Before ES6 there were only one way of defining your variables: with the var keyword. If you did not define them, they would be assigned to the global object, unless you were in strict mode, in which case you would get an error if your variables were undefined.

In ES6, you define variables with var, let, or const.

var

var has a function scope, not a block scope.

let

let has a block scope.

const

const has a block scope.


React Render HTML

React provides a function called ReactDOM.render() which you can use to display some HTML code inside an HTML tag that you specify.

ReactDOM.render() takes two arguments:

  1. Some HTML code; and
  2. The tag in which you want to display the HTML code.

As an example, you can use this code to display a paragraph inside a tag with an id attribute of "root":

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

If the HTML code that you want to display has multiple tags in it, you use a syntax like the following (called JSX syntax):

    const myelement = (
      <table>
        <tr>
          <th>Name</th>
        </tr>
        <tr>
          <td>John</td>
        </tr>
        <tr>
          <td>Elsa</td>
        </tr>
      </table>
    );

    ReactDOM.render(myelement, document.getElementById('root'));

Please NOTE that the tag in which you display the HTML code does NOT need to be a <div> tag.

Also please NOTE that the id attribute of the tag in which you display the HTML code does NOT need to be "root".


React JSX

JSX stands for JavaScript XML.

JSX allows you to more easily write and add HTML code in React.

JSX is an extension of the JavaScript language based on ES6, and is translated into regular JavaScript at runtime.

You are NOT required to use JSX, but JSX makes it easier to write React applications.

Following is an example of adding an H1 tag to the 'root' tag, WITHOUT JSX:

    const myelement = React.createElement('h1', {}, 'I do not use JSX!');

    ReactDOM.render(myelement, document.getElementById('root'));

And now, following is an example of adding an H1 tag to the 'root' tag, WITH JSX:

    const myelement = <h1>I Love JSX!</h1>;

    ReactDOM.render(myelement, document.getElementById('root'));

Expressions in JSX

If you need to display the results of, for instance, a mathematical calculation in the HTML code, you can use a JSX Expression. JSX Expressions use curly braces to contain the calculation or property or JS variable.

For example, the following code would display the results of the mathematical computation 5 + 5:

    const myelement = <h1>React is {5 + 5} times better with JSX</h1>;

The previous section, "React Render HTML", shows you how to code multiple HTML tags into JSX. Please review that section.

Single Top-Level Tag

Please NOTE that the HTML code that you create in JSX must have ONE top-level tag.

So if you have multiple HTML tags to insert, you must wrap them in another container tag, such as a <div> tag or a <table> tag.

Tags Must Be Closed

JSX follows the normal XML rules, so all HTML tags in JSX code must be closed.

What this consideration means for self-closing tags is that they must end with />.


React Components

React Components are resusable blocks of code. They are similar to JavaScript functions, but they return HTML code with a render function.

There are two types of React Components:

  1. Class components; and
  2. Function components

Class Components

Here is an example:

    class Car extends React.Component {
      render() {
        return <h2>Hi, I am a Car!</h2>;
      }
    }

To use this Car component, simply use syntax that is very similar to regular HTML, like this: (Please NOTE the first argument in the call to ReactDOM.render().)

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

Function Components

Here is an example of creating a Function Component:

    function Car() {
      return <h2>Hi, I am also a Car!</h2>;
    }

And now here is an example of how you could use this Function Car component (which is just the same as how you use a Class Component):

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

Component Constructor

You can include a contructor() function in your Class Component. When the Class Component gets created by the React code, the constructor() function gets called. You can initialize the component's properties in this constructor() function.

As we will see just a bit later, the component's properties are put into a state object.

You also need to call the super() function in the constructor function. This call to super() causes the parent component's constructor function to be called. It also makes available to your Class Component, all of the functions that are in the parent component, which is React.Component.

Following is an example, which includes a constructor function, which has a property called color. This color property is used in the render() function:

    class Car extends React.Component {
      constructor() {
        super();
        this.state = {color: "red"};
      }
      render() {
        return <h2>I am a {this.state.color} Car!</h2>;
      }
    }

Props

Component properties can also be used as props. Props are like function arguments. See the following section, Props, for more information.


React Props

Props are information (arguments) sent into a React component, as HTML attributes.

For example, you could send a "brand" prop into a Car tag like this:

    const myelement = <Car color="Red" />;

And the "brand" attribute becomes a props object in the component, like this:

    class Car extends React.Component {
      render() {
        return <h2>I am a {this.props.color} car!</h2>;
      }
    }

Sending Data into a Component

You can also send data into a Component from another Component. You can use props to do so.

As an example, you could send a "color" property from a "Car Dealer" component, into the "Car" component, like this:

    class Car extends React.Component {
      render() {
        return <h2>I am a {this.props.color} car!</h2>;
      }
    }

    class Dealer extends React.Component {
      render() {
        return (
          <div>
          <h1>What color cars are available?</h1>
          <Car color="Blue" />
          </div>
        );
      }
    }

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

Using a Variable as a Prop

You can also use a variable as a prop, by putting curly braces around the variable name. Here is an example:

    class Car extends React.Component {
      render() {
        return <h2>I am a {this.props.color} car!</h2>;
      }
    }

    class Dealer extends React.Component {
      render() {
        const carcolor = "Green";
        return (
          <div>
          <h1>What color cars are available?</h1>
          <Car color={carcolor} />
          </div>
        );
      }
    }

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

Using an Object as a Prop

You can also send information as a prop, into a component, using an object.

Here is an example:

    class Car extends React.Component {
      render() {
        return <h2>I am a {this.props.brand.color} {this.props.brand.model}!</h2>;
      }
    }

    class Dealer extends React.Component {
      render() {
        const carinfo = {color: "Pink", model: "Camry"};
        return (
          <div>
          <h1>What kinds of cars are available?</h1>
          <Car brand={carinfo} />
          </div>
        );
      }
    }

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

Props in a Constructor

Components that have a constructor function should receive data into the constructor via props and the super() method, like this:

<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="utf-8" />
  <meta name="viewport" content="width=device-width, initial-scale=1" />
  <title>React App</title>
  <script src="https://unpkg.com/react@16/umd/react.production.min.js"></script>
  <script src="https://unpkg.com/react-dom@16/umd/react-dom.production.min.js"></script>
  <script src="https://unpkg.com/babel-standalone@6.15.0/babel.min.js"></script>
</head>
<body>

  <div id="root"></div>

  <script type="text/babel">
    class Car extends React.Component {
      constructor(props) {
        super(props);
      }
      render() {
        return <h2>I am a {this.props.color} {this.props.model}!</h2>;
      }
    }

    ReactDOM.render(<Car model="Mustang" color="Red" />, document.getElementById('root'));
  </script>
</body>
</html>

React State

React components have a built-in state object.

The best place in which you should store your property values is in the state object.

When the state object changes, the browser re-renders the component.

You create and initialize the state object in the constructor. You can put as many properties as you need, into the state object, like this:

    class Car extends React.Component {
      constructor(props) {
        super(props);
        this.state = {
          brand: "Ford",
          model: "Mustang",
          color: "red",
          year: 1964
        };
      }
      render() {
        return (
          <div>
            <h1>My {this.state.brand}</h1>
            <p>
              It is a {this.state.color}
              {this.state.model}
              from {this.state.year}.
            </p>
          </div>
        );
      }
    }

Please note, in the above code, that the syntax for using the properties in the state object is like this:

    this.state.propertyname

Changing the State Object

If you need to change a value in the state object, you use the method this.setState()

When a value in the state object changes, the browser will re-render the page, displaying the new value. Here is an example:

    class Car extends React.Component {
      constructor(props) {
        super(props);
        this.state = {
          brand: "Ford",
          model: "Mustang",
          color: "red",
          year: 1964
        };
      }
      changeColor = () => {
        this.setState({color: "blue"});
      }
      render() {
        return (
          <div>
            <h1>My {this.state.brand}</h1>
            <p>
              It is a {this.state.color}
              {this.state.model}
              from {this.state.year}.
            </p>
            <button
              type="button"
              onClick={this.changeColor}>Change color</button>
          </div>
        );
      }
    }