React Tutorial

Why React is Better

React is a JavaScript library for building user interfaces. It helps when your web page needs to update and change without constantly refreshing.

Advantages of React When to Use React When React Might Be Overkill In Short

React is better when your app is dynamic, interactive, and grows in complexity.
If it's static and simple, plain HTML/CSS/JS is often enough.

React vs Plain HTML/JS

Feature React Plain HTML/JS
Reusability Build reusable components and use them anywhere. Repeat code or copy-paste; no built-in reusability.
Dynamic Updates Automatically updates only the changed parts of the UI (virtual DOM). You must manually manipulate the DOM with JavaScript.
Data Handling State and props make data flow predictable. No built-in system; must manage variables and DOM updates manually.
Scalability Designed for complex, interactive apps with many components. Gets messy as apps grow; hard to maintain and debug.
Best For Interactive, data-driven apps that change often. Small static sites or simple interactivity.

The React Tutorial

I have created a basic React tutorial below. For a full React tutorial, see W3Schools React Tutorial.

All React examples given in this tutorial assume no server. For React without a server, be sure to include the appropriate headers in all scripts and that any script inside your body be of type text/babel:

<head>
    <script src="https://unpkg.com/react@18/umd/react.development.js" crossorigin></script>
    <script src="https://unpkg.com/react-dom@18/umd/react-dom.development.js" crossorigin></script>
    <script src="https://unpkg.com/@babel/standalone/babel.min.js"></script>
</head>

<!--Any script inside your body should be of type text/babel-->
<body>

    <div id="mydiv"></div>

    <script type="text/babel">
    </script>

</body>

To avoid the Cross-Origin Request Blocked error, start a local http-server:

  1. Install http-server by typing npm install -g http-server
  2. Change into your working directory, where yoursome.html lives
  3. Start your http server by issuing http-server
  4. You could access your file as: http://127.0.0.1:8080/FileName.html

React creates a VIRTUAL DOM in memory. Instead of manipulating the browser's DOM directly, React creates a virtual DOM in memory, where it does all the necessary manipulating, before making the changes in the browser DOM. React only changes what needs to be changed! React finds out what changes have been made, and changes only what needs to be changed.

Simple Examples

The first example is a simple Hello World: HelloWorld.html, HelloWorld.js. Note that the HTML code simply provides a root div, within which React generates the HTML code.

The second example shows how to render a simple table with React: Render.html, Render.js.

The third example shows one component invoking another: Component.html, Component.js.

Classes

The following examples show the use of classes with React. As you can see, each class derives from React.Component: Car.html, Car.js.

React.Component gives your class access to all the functionality of React components, such as:

So in short, React.Component is a blueprint provided by React for creating components. By extending it, your classes (Car, Garage) become React components that React knows how to render into the DOM.

The next example shows a class with properties (variables), to form a complete class. It also shows a simple button handler: Car2.html, Car2.js.
For a deeper look at properties, see: CarInfo.html, CarInfo.js.

The next example shows a class that can alter the state of one of its components: DelHeader.html, DelHeader.js.

This final example shows a class that attempts to alter the state of one of its components, but such alteration depends on the function shouldComponentUpdate(): FavColour.html, FavColour.js,

Events, Lists, Forms

The following code shows handling a simple event with React: Football.html. Football.js.

The following code shows the handling of lists with React: CarList.html, CarList.js.
But this code shows how it would be done without React, with HTML and JavaScript: CarList.html.

Why React is Better

The following code shows the handling of forms with React: MyForm.html, MyForm.js.
Note the first line: const { useState } = React; which is a JavaScript destructoring assignment. React provides many features as named exports from the React object (like useState, useEffect, useContext, etc.). By writing {useState}=React, you are pulling just the useState function out of the React object. This allows you to call useState(...) directly, instead of having to write React.useState(...) every time.

Hooks

React Hooks make functional components powerful - they can now manage state, handle lifecycle events, and use context, all without needing classes. Before hooks, class components were needed for state and lifecycle methods, and functional components were "stateless" and much simpler. Hooks allow you to use state and other React features inside functional components, so you no longer need to write classes for most cases.

Here are some common hooks:

  1. useState: Lets you add state to a functional component:
    const [count, setCount] = useState(0);
    count is the state value; setCount is the function to update it.
  2. useEffect: Runs side effects (e.g., data fetching, subscriptions, manipulating the DOM).
    useEffect(() => {
      console.log("Component mounted or updated");
      return () => console.log("Cleanup on unmount");
    }, []);
  3. useContext: Allows you to access context values without writing wrappers.

The first example uses the useState hook to store the current favorite color, update it in response to button clicks, and automatically re-render the UI when the state changes: favColour.html, favColour.js.

The second example uses the useState hook to manage a complex object as state. It initializes state with an object, updates state immutably using the setter function and spread operator, and automatically re-renders the UI when state changes: Car.html, Car.js.

The third example uses useState to hold and update the timer count, and useEffect to schedule side effects (a timeout that updates the count): Timer.html, Timer.js.

The fourth example uses useState to hold and update two independent state variables (count and calculation), and useEffect to automatically update calculation whenever count changes. So instead of recalculating count*2 directly in JSX, the effect ensures the calculation state is always derived and kept up to date.: Counter.html, Counter.js.

The fifth example makes use of hooks in two ways. useState in Component1 manages a piece of state (user). useContext in Component5 consumes that state from a context provider, avoiding prop drilling. So the hook flow looks like this: Component1 creates state (useState) and shares it via context provider, and Component5 retrieves that shared state with useContext. The code can be seen here: Component.html, Component.js.

This last example shows polymorphism with React. The common interface is the VehicleUI. The derived classes are Car, Truck, and Van. The code can be seen here: VehicleUI.html, VehicleUI.js.

React Equivalents to JavaScript

In the JavaScript tutorial, we saw a webpage that calculates the average of three marks. We could write this with React, as follows: Average.html, Average.js.

In the JavaScript tutorial, we also saw a webpage that can be used for an employee database. In React, this would be written as: Employee.html, Employee.js.

In the JavaScript tutorial, we saw a webpage that fetched images of dogs off the internet. In React, this would be written as: dogs.html, dogs.js.

In the JavaScript tutorial, we also saw a webpage that retrieved the value of Bitcoin from an API. In React, this would be written as: Bitcoin.html, Bitcoin.js.

The Tic Tac Toe Application

A fully working tic tac toe application has been written in HTML and JavaScript, using React. This application draws a tic tac toe board and allows user input. After each input, the application determines if there has been a winner. Each play is recorded so one can go back in history to see how the game unfolded. The application is found here:
styles.css, TicTacToe.html.