Learning ReactJs – A Basic Overview

Note: This post is work-in-progress learning-note and still in active development and updated regularly.

After React development environment setup, I wanted to dig into React world. React API is known as most popular JavaScript (JS) library to allow developers to build interactive user interfaces for webs.

Build encapsulated components that manage their own state, then compose them to make complex UIs. React Website

Before deep diving into React, I wanted have a quick overview of React’s component-based structure first, just enough to getting started. Main purpose of this introductory learning-note post is to get familiar with basic ReactJs terminology with an aim to understand workings of a React component enough to getting started with building basic react applications.

React DOM – a Virtual DOM

It’s React way to using DOM as a virtual representation of UI “virtual DOM”, which is an abstraction of HTML DOM.Updating elements on DOM nodes involves using DOM UI. Frequent update of elements on node tree slows down element rendering on the DOM.

React gets around this problem using virtual DOM, which is build on the top of the actual DOM. Most events updating in React occur in virtual DOM and utilize minimum use of HTML DOM. Events update from virtual DOM to actual occurs through reconciliation and thus achieve faster and efficient implementation.

Additional Resource: React DOM

Elements

React elements are considered the building blocks of ReactJs and are returned using render() method to the viewing post (screen). The elements are immutable (can be modified). An example of react element:

// react element
const element = <h1>Greetings, You are awesome!</h1>;

Additional information: Rendering Elements

Using JSX

React uses JSX (JavaScript XML) to  describe user interface. Although React recommends using JSX, it is optional and not required to use React.

1. Nested Elements in JSX

Nested elements should be wrapped inside a container wrapper.

// nested wrapper in JSX
<div>
    <h1>Hello World!</h1>
    <h2>Welcome to ReactJs app</h2>
    <p>This is nested element use in JSX</p>
</div>

In the example above, the h1, h2 and p elements are wrapped with div element.

Alert: If two JSX elements are used in a component to return elements, Babel compiler throws error. A return() method returns only single parent element.

// use of nested sibling elements - throws error
const MyExample = () => {
    return (
       <div> Hello, World!</div>
       <div> Hello, me again!</div>
       )
}

//babel transpile error
repl: Adjacent JSX elements must be wrapped in an enclosing tag (5:7)
  3 |     return (
  4 |        <div> Hello, World!</div>
> 5 |        <div> Hello, me again!</div>
    |        ^
  6 |        )
  7 | }

When Babel transpiles a JSX tag it turns into a function and returns  the result of React.createElement(). As we know return keyword serves as break point, it’s not allowed to have two return statements inside a component.

Return JSX elements inside components must be wrapped within a single parent div as shown below:

// Babel transpiles WITHOUT error
const MyExample = () => {
    return (
     <div>
       <div> Hello, World!</div>
       <div> Hello, me again!</div>
    </div>
       )
}

Tip: When in doubt using JSX inside render() method, wrap all elements inside a single div element.

2. HTML Attributes in JSX

React DOM supports standard or custom DOM attributes with or without data- prefix attributes. Using the examples from React Documentation:

//example from React Documentation
<div tabIndex="-1" />      // Just like node.tabIndex DOM API
<div className="Button" /> // Just like node.className DOM API
<input readOnly={true} />  // Just like node.readOnly DOM API

//use of data attributes
<div data-foo="42" />
<button aria-label="Close" onClick={onClose} />

Addition Information: React DOM Elements

3. Use of JS Expression in JSX

JS expression can be used in JSX but the expression should be wrapped within { } curly brackets.

// ES6 syntax
const MyExample = () => {
    let name = "Toyota"
    return (
       <h1> I drive {name}</h1>
       )
}

In the example above, simple JS expression name = "Toyota" (line 3) is wrapped with curly braces { } in  JSX (line 5).

Addition information: Embedding expression in JSX

4. Comments in JSX

HTML comments can’t be used in JSX. The following HTML comment (line 5) throws error.

// HTML comments throws error
render() {
  return (
    <div>
      <!-- This doesn't work! -->
       <h1>Hello World!</h1>
    </div>
  )
}

In JSX regular JS block comments /* JS block comment */ can be used but they need to be wrapped with curly brackets { } as shown below:

// single line JSX comment
{/* A single line JSX comment */}

//Multi-line JSX comments
{/* Multi-line comments
 in JSX looks
like this example
*/}

5. Inline Styling in JSX

Inline style can be added to React App by combining CSS style with JSX as shown in the example below:

/* inline styling */
class HelloWorld extends React.Component{
   render() {
    {/* inline style */}
    var addStyle = {
         fontSize: 40,
         fontWeight: bold,
         color: '#0080ff'
      }

      return <div>
        <h1 style = {addStyle}>Hello World!</h1>
        <p>This is simple React Component</p>
        </div>
      }
}

The <strong>camelCase</strong> naming convention is used in CSS syntax, px value will be automatically added by React after appropriate value in an element. In the above example addStyle (lines: 5-9) is used to inline styling of h1 element (line 12).

Note: To quote from the React Documentation: “Since JSX is JavaScript, identifiers such as class and for are discouraged as XML attribute names. Instead, React DOM components expect DOM property names such as className and htmlFor, respectively”.

Additional information: DOM Elements

Components

In React World, everything is component which are essentially JS functions and Classes. To quote from React DocumentReact components are small, reusable pieces of code that return a React element to be rendered to the page“.

Its a general convention to start first letter of component names with capital letter. React components can be group into Functional and Class components.

1. Functional component

The functional components is the classic JS function which accepts single property (referred as “props” in react) object argument with some data and returns JSX element.

//functional component
const Greeting = () => { 
    return <h1>Greeting, You look awesome!</h1>;
}

// stateless component
function Welcome(props) {
  return <h1>Hello, {props.name}</h1>;
}

Functional components are referred as “stateless” component because they lack state & life cycle methods is not aware of any of its own state. Its main purpose to receive data and present as JSX. Their main objective is “presentational“, i.e. to alter the UI.

The stateless components are simple, easy to write & understand and recommended to use when there is no need to use state or life cycle methods. They are suitable to build presentational components.

2. Class Components

React class components, unlike functional components, are aware of its state such as user responses (clicking a button or entering data etc).

Class-based components are basically JS classes and which extends React.component and uses render() method (a required method) to return JSX.

// using class component
class Greeting extends React.Component {
  render(){
    return <h1>Greeting, You are awesome!</h1>;
  }
}

// ES6 Classes component
class Welcome extends React.Component {
  render() {
    return <h1>Hello, {this.props.name}</h1>;
  }
}

In the example above, the  return statements (lines: 4 & 11) are in one line and thus does not require a parentheses. In react world, the above two methods are equivalent.

Class-based components are referred as “stateful” because they contain additional state & life cycle methods. In a typical class-based component, its state consists of class constructor method, <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Classes#Super_class_calls_with_super" target="_blank" rel="noopener">super</a> class inside the <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Classes#Constructor" target="_blank" rel="noopener">constructor</a> method.

An example of class-based component from React Guide:

//example from React guide
class Clock extends React.Component {
  constructor(props) {
    super(props);
    this.state = {date: new Date()};
  }

  render() {
    return (
      <div>
        <h1>Hello, world!</h1>
        <h2>It is {this.state.date.toLocaleTimeString()}.</h2>
      </div>
    );
  }
}

A class-based component has state, life cycle methods, and  every time React renders it creates an instance of a class component.

Additional Information: Components and props & Should this Component have state?

More detail discussion on rendering a component, working example of a component, and extracting a component will be discussed separately.

Props and State

The React document describes <strong>props</strong> as ” inputs to a React component. They are data passed down from a parent component to a child component.”

Props

Props are immutable (read-only) object properties of component (functional or a class) which are displayed in DOM with render() method in JSX element.

Props are passed from from one component to another, say from parent components to child component (one directional flow from top to down). Example of props data include data, callback function.

Once received by components they must never be modified or changed. The following example snippets adapted from the React:

//function component
function add(x, y) {
  return x + y;
}
//mutable (impure) function
function substract(account, amount) {
  account.total -= amount;
}

In the example above, the return value of add() function always remains the same for the same inputs and thus also called “pure” function. However, in the substract() function (lines: 6-8), the value of account.total changes. The props in React components must operate as pure (immutable) functions.

State

To quote from the React document, “state is similar to props, but it is private and fully controlled by the component“.

The state object properties in React components are mutable, which means that state property value in response to user input or other responses.

State is always a part of a React component (internal data of a class) and any data belonging the state effect only the components below. This process is commonly referred as “top-down” or “unidirectional” data flow.

By default, React component has no state. The following example (used in earlier section) is stateless component:

//stateless component
function Welcome(props) {
  return <h1>Hello, {props.name}</h1>;
}

If any React App such as clicking a button, or to do list etc needs to keep track of user responses then a state can be created to update and keep track of events.

An use case example of how state in React component ticking clock from React guide is available in CodePen.

Additional Information: State and Lifecycle,  and ReactJS: Props vs. State

Difference between Props and State

The difference between Props and State summarized in the following table is adapted from Props vs State from React Guide GitHub pages.

Description Props State
Can get initial value from parent Component? Yes Yes
Can be changed by parent Component? Yes No
Can set default values inside Component?* Yes Yes
Can change inside Component? No Yes
Can set initial value for child Components? Yes Yes
Can change in child Components? Yes No

Other React Terminology

The other React terminology like Life Cycle methods, Controlled vs controlled components, Keys, Refs, Events & Reconciliation will be discussed separately.

Starting to Thinking in React Way!

In an effort to start learning React by building react components, it’s time to start thinking in React way by building simple applications and learn step by step to build more complex applications.

Wrapping Up

In this learning-note post, basic React terminology and an overview of these concepts were briefly discussed. The next step to start using these concepts to build a simple React applications.

NEXT: Learning to Work With React Components

Useful Resources and Links

While preparing this post, I have referred the following references extensively. Please to refer original posts for more detailed information.