Let's start by asking some questions concerning React.

What is React?

React is a JavaScript library for building user interfaces created by Facebook. According to Wikipedia, a software library  is a collection of non-volatile resources used by computer programs, often for software development. These may include configuration data, documentation, help data, message templates, pre-written code and subroutines, classes, values or type specifications. A User interface is a means by which the user interacts with the computer.

Why use React?

Aside from React, there are other technologies for building user interfaces such as Angular, Ember, Vue, jQuery etc.The following are reasons why a developer should choose React.

React is fast

React uses Virtual DOM to render elements. Virtual DOM is a lightweight copy of a real DOM, which through the declarative API and the diff algorithm compares those elements that need to be modified with the help of observables, and then redraws only them. This speeds up the performance of React Applications. AngularJS uses dirty checking to discover nodes that need to be redrawn. The dirty checking does not begin immediately; this slows down performance. React Application performance can also be improved on by using production build, separation to chunk files, and Gzip compression.

React has a Large Ecosystem

React Ecosystem is a community of technologies that interact with each other while building React applications. Some of these technologies in the React ecosystem include the following Jest (A  JavaScript testing framework), Gatsby(Site generator for React), NextJS(React Server-side Rendering), Parcel(Code bundler), Yarn(Package Manager), NPM(Package Manager), Webpack(Code Bundler), Babel(Transpiler), Eslint(Linter), Typescript(Static Scripting Language), Redux(State Container for JavaScript Apps), Flux(Data Flow Manager), Prettier(Code Formatter), React-Router( collection of navigational components that compose declaratively with your application) etc. Large ecosystem means extensive usage of the technology and also solutions to challenges faced using the technology.

React uses Declarative Language

According to Wikipedia, Declarative programming is a programming paradigm — a style of building the structure and elements of computer programs—that expresses the logic of a computation without describing its control flow. This programming paradigm makes programming more readable and easier to reason.

React has a small API

React has a small API. The file size of React API compared to other UI libraries and frameworks is small. The React library also contains fewer API's. This has helped developers to learn all of the React Libraries compared to other libraries like Angular which is almost next to impossible.

React separates concerns

Instead of separating technologies into separate files like other UI libraries and frameworks, React approaches UI design from a different perspective. Before React, UI design involved the use of JavaScript, HTML and CSS files, React merges HTML, JavaScript and CSS into one piece. React is concerned with the part of the UI, and not the separate technologies.

Using React in UI Design

React is very flexible.  Little or much of React can be used in a project. A UI can be built solely on React or React plus other UI technologies. The following are ways to add React to a project.

Method 1: Using Script Tags

Adding React using script tags is usually a practice used by beginners for learning React, and this method is also used to introduce React to an already existing project. Below is an example of a simple code snippet for adding React to a development page and to production page.

For development

<!DOCTYPE html>
<html>
  <head>
    <meta charset="UTF-8" />
    <title>Hello World</title>

    <script src="https://unpkg.com/react@16/umd/react.development.js" crossorigin></script>
    <script src="https://unpkg.com/react-dom@16/umd/react-dom.development.js" crossorigin></script>
    <script src="https://unpkg.com/babel-standalone@6/babel.min.js"></script>
    <link rel="stylesheet" href="style.css">

  </head>
  <body>
	<! Other codes>
    <div id="root"></div>

    <script type="text/babel" src="index.js">
    </script>
  </body>
</html>

For production

<!DOCTYPE html>
<html>
  <head>
    <meta charset="UTF-8" />
    <title>Hello World</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/babel.min.js"></script>
  </head>
  <body>
    <div id="root"></div>
    <script >
    </script>
  </body>
</html>

Method 2: Using Toolchains

React can be added to a project using Toolchains. According to Wikipedia, a toolchain is a set of programming tools that is used to perform a complex software development task or to create a software product, which is typically another computer program or a set of related programs. Toolchains are also used for learning React, building server-rendered websites, static content-oriented websites and for Single Page Applications. Toolchains include the following create-react-app, Next.js, and Gatsby. Create-react-app  from Facebook is one of the most used toolchain for creating React applications.

Method 3: Building Development Environment from the scratch.

This involves adding individual tools needed for the React project such React Library, A bundler (Webpack or parcel), Babel (a Transpiler), Jest ( A test runner), etc. manually without a toolchain.

Tools Needed for this Tutorial

  • Create-react-app toolchain: Toolchain for building React development environment.
  • VScode: A code editor for writing our code .
  • Node and Npm: Package manager for managing our dependencies.
  • React Developer Tool: used in debugging React code.
  • Git: for version control

How to set up a Development Environment for this tutorial

  • Step1: Download and install nvm (node version manager) :

https://github.com/nvm-sh/nvm#git-install (this step is not necessary for Windows users). To verify that nvm is installed in your computer run the following command in the terminal,

nvm -v

  • Step 2: Download and install Node and npm. npm is installed along side Node.

For Linux users: You can install node and nvm by running the following command in the terminal.

nvm install node

For Windows: You can download .msi or the binary from here

To confirm that node and npm are installed In your computer.

In the command line type

"node -v " and press enter.

The command line displays the version of node installed on your computer. Also type “npm -v” in the command line, the computer displays the version of npm installed on the computer.

  • Step3: Download and install git from here
  • Step 4: Download and install VScode from here
  • Step 5:  Install React Developer Tool for the browser installed in the computer. Preferably you can install Mozilla Firefox or google chrome browser in the computer.

For Google chrome developer tools install extension here

  • Step 6: Install create-react-app globally, In the terminal type.

npm i -g create-react-app

  • Step 7: Open the terminal and navigate to a location in the computer where you want to create the the local repository and type “create-react-app building-components” and enter. This creates a development environment that contains other tools such as Eslint(a linter), Jest(A test), Webpack(a bundler), and Babel(a transpiler)
  • Step 8: Open the “building-components” folder using vscode.
  • Step 9: In terminal type “npm install” to install dependencies
  • Step 10: Delete the content of the folder “src” and create the file “index.js” in the src folder.
  • Step 11: Open index.html in the folder “public” and delete the content of the file and paste the following code.
<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>Document</title>
</head>
<body>
  <div id="root"></div>
  
</body>
</html>

Rendering Items to the UI using React.

According to Wikipedia rendering is the process of generating a photorealistic or non-photorealistic image from a 2D or 3D model by means of a computer program. React generates the UI from Javascript code which acts as the model of what is to be rendered. ReactDOM.render API renders an element to the browser and ReactDOMServer APIs (ReactDOMServer.renderToString, ReactDOMServer.renderToStaticMarkup, ReactDOMServer.renderToNodeStream, ReactDOMServer.renderToStaticNodeStream) renders on the server. The concept of React being able to render on the browser and also on the server is known as isomorphism. Before React, a description of the UI is done in the markup and the UI logic is done in a JavaScript file but React combines the markup, CSS and the logic as one. The item passed to ReactDOM.render and ReactDOmServer is a description of what is to be rendered in the DOM or in the server. In this tutorial we shall be concerned with rendering in the DOM.

- How to render an item on the browser

Step 1: Open the index.js file in the src folder of building-components.

Step 2: Delete the content of the file and paste the following code.

import React from "react";
import ReactDOM from "react-dom";

const element = <h1>my element</h1>;

ReactDOM.render(element, document.getElementById("root"));

Step 3: Open the terminal in project root folder type “npm start” and press enter.

Step 4: Check the rendered page on the browser

The usage of ReactDOM and ReactDOMServer are actually function calls in Javascript. The items passed to them as arguments are actually Javascript data values (primitives values and object values).

In Javascript, a function call can take any one of Javascript data types as arguments. Data types in Javascript consist of Undefined (undefined) , Null (null), Boolean(true, false), Number, String, Symbols, Objects and functions (These are callable objects).

The following describes how React renders the datatypes passed as argument.

- React does not render undefined, null and Boolean values. Booleans values can be used for program flow control and null can be used for cases where nothing is to be rendered.

- React renders String and Numbers as text nodes in the DOM.

- React renders arrays as multiple sibling elements.

- React fragments allow the rendering of sibling elements without a parent.

- React portal allows the rendering of children from another DOM

ReactDOM takes a model(a representation or description of the things we want to be in the display) and renders them to the display (browser).  React element is a description or representation of the things we want to be in the display. A React element can be simplified as JavaScript objects with the following properties.

const element = {
    type: 'h1',
    props: {
        className: 'greeting',
        children: 'Hello, world!'
    }
};

How to Create A React Element

React Elements can be created using the following methods

Method 1: By calling

React.createElement()

To create a React element using React.createElement() call,

- Call React.createElement(type, [props], […children]) inputting the value for type, [props] and […children]. “type” represents a DOM tag or a component, [props] is  the properties of the DOM tag or component, …children represents children of the DOM tag or component. A component name is normally written Starting with A capital letter while DOM tags are written in small letter as strings.

DOM tag element

React.createElement(
"div",
{ className: "container" },
"This is DOM tag element"
);

Component element

An Example of Component element

React.createElement(
  MyComponent,
  { name: "My name props" },
  "Component children"
);

Method 2: Creating React Element using JSX

JSX looks like xml. It was developed as an ES6 language feature (ES6 extension).

To create a React element using JSX, use the following format

<element name element attributes>element children</element name>

- Other JSX format styles are included in the JSX specification. A component name is normally written Starting with A capital letter while DOM tags are written in small letter as strings.

const element = <div>DOM Tag </name>
	
	Component element
const element = <MyComponent name="Component">My Children</MyComponent>;

JSX element compiles to React.createElement() calls and React.createElement() return React Element Objects. JSX is commonly used when developing React Applications since it is easier to write compared to React.createElement() and It is also easy to detect errors using JSX.

Components

A component is function that accept a single input and returns React element.  It is also a JavaScript class that has a render method that returns React element.

How to Create A React Component

A React Component can be created using the following methods:

Method 1: Creating a React Component Using JavaScript function

To create a React component, define a JavaScript function that takes a single parameter named props and returns a React Element.

// Using A function Statement Declaration 
function MyComponent(props) {
  return <h1>This is a Component</h1>;
}

// Using function Expression 
const MyComponent = function (props) {
  return <h1>This a Component</h1>;
};

// Using Arrow function Expression 
const MyComponent = function (props) {
  return <h1>This is a Component</h1>;
};

Method 2: Creating a React Component using JavaScript Class

To create a React component using JavaScript, define a JavaScript class that has a render method that returns a React element.

class MyComponent extends React.Component {
  render() {
    return <h1>This is a Component</h1>;
  }
}

Props

Props are React element properties. Props allow us to pass values of any type to a React element.

The element attributes and the element children are all passed as a single object called props.

How to pass props  to an element

Step 1: Define the component(function or class component) with a single parameter props and using the object notation and curly braces to embed the props where the props will be used in the element.

Step 2: State the attributes and the children while creating the element.

function MyComponent(props) {
  return (
    <>
      <h1>this is name attribute {props.name}</h1>
      <h1>this is props children {props.children}</h1>
      <h1>this is another attribute {props.another}</h1>
    </>
  );
}

ReactDOM.render(
  <MyComponent name="Robin" another="Jane">
    my children
  </MyComponent>,
  document.getElementById("root")
);

Events

According to Wikipedia, in programming and software design, an event is an action or occurrence recognized by a software, often originating asynchronously from an external environment, that may be handled by the software. One of the strengths of React is the ability to handle events. React events are synthetic events different from native browser events. React events work on all browsers.

How to create react events

  • Creating A React Event for function component element and DOM element
  1. Create a function component element or DOM element.

2.  Add an event to the element as part of it attributes and assign to the event a handler . The handler (A function ) should be in scope with the element. Ensure that the event name is written in Carmel case.

function App(props) {
  return <h1 onClick={props.onClick}>This an App</h1>;
}

function Handler() {
  console.log("clicked");
}
  • Creating A React Event for class component element

1.      Define a class component.

2.      Add the constructor (props) method

3.      Call the super (props)

4.      Bind the handler to this

5.      Create the handler method as part of the class method

6.      Create an event

7.      Assign a handler to the event using this keyword.

class App extends React.Component {
  constructor(props) {
    super(props);
    this.handleClick = this.handleClick.bind(this);
  }

  render() {
    return <h1 onClick={this.handleClick}>Click this </h1>;
  }

  handleClick() {
    console.log("clck");
  }
}

Application

In this section, We will apply the knowledge from the previous sections. We will build a simple counter application. We will be using the React Environment we have set up.

  • Paste the following in index.js
import React from "react";
import ReactDOM from "react-dom";

let count = 0;

function increment() {
  count = count + 1;
  ReactDOM.render(<App count={count} />, document.getElementById("root"));
}

function decrement() {
  if (count - 1 >= 0) {
    count = count - 1;
  }

  ReactDOM.render(<App count={count} />, document.getElementById("root"));
}

function reset() {
  count = 0;

  ReactDOM.render(<App count={count} />, document.getElementById("root"));
}

function App(props) {
  return (
    <>
      <h1 className="display">{props.count}</h1>
      <button onClick={increment} className="btn">
        increment
      </button>
      <br />
      <br />
      <button onClick={decrement} className="btn">
        decrement
      </button>
      <br />
      <br />
      <button onClick={reset} className="btn">
        reset
      </button>
    </>
  );
}

ReactDOM.render(<App count={0} />, document.getElementById("root"));
  • In the public folder create style.css and paste into it the following code.
.btn {
    width: 100px;
}

.display {
    width: 100px;
    color: red;
    text-align: center;
    border-style: solid;
    border-width: 1px;
}
  • Paste the following code in index.html in the public folder.
<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="UTF-8" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <link rel="stylesheet" href="style.css" />
    <title>Building Components</title>
  </head>
  <body>
    <div id="root"></div>
  </body>
</html>

When we run the above application code it displays the counter application below

Summary

We have covered fundamentals of React and with a sample application.

React is used for building rich web applications. So much to be covered in regards to building applications with React. I will be posting subsequent articles on building applications with React.

Engage with me on the comment section for more discussions on React.

References:

Component based Software Engineering https://en.wikipedia.org/wiki/Component-based_software_engineering

React Documentation - https://reactjs.org

JSX in Depth - https://reactjs.org/docs/jsx-in-depth.html

React Component - https://reactjs.org/docs/react-component.html

JSX specification - https://facebook.github.io/jsx/

Event Computing - https://en.wikipedia.org/wiki/Event_(computing)

React: The Big Picture – Cory House – www.pluralsight.com

React: Getting Started – Samer Buna – www.pluralsight.com

React Fundamentals  - Liam McLennan – www.pluralsight.com

You've successfully subscribed to Decoded For Devs
Welcome back! You've successfully signed in.
Great! You've successfully signed up.
Your link has expired
Success! Your account is fully activated, you now have access to all content.