Understanding React (Routing) with your Angular Knowledge

Written by xthecapx | Published 2019/08/31
Tech Story Tags: react-routing | react | angular | react-learning-guide | angular-developer | react-template | what-routing-means | latest-tech-stories

TLDR In this series, I’ll provide you all the steps to develop the “Getting Started with Angular: Your First App” using React. In this tutorial, we review the essential elements of the React template, the prop system, and the communication channel between parent and children components. We need to overwrite the default behavior of the server routing system. In React, we are the kings, aren’t we? In Angular, you must use the tools provided by the Angular Team.via the TL;DR App

Welcome to my React learning guide if you’re an Angular developer. On this series, I’ll provide you all the steps to develop the “Getting Started with Angular: Your First App” using React.
In the last lecture, we review the essential elements of the React template, the prop system, and the communication channel between parent and children components.
Now is time to talk about the routing.

What routing means?

In traditional web development, Routing is a concept related to the physical location of the files required to display an application. If a user wants to render a page, the Browser clears the window document and updates everything with the information provided by the server.
If you review the real path of a file inside a server, it will include many characters (something like https://12.123.13.243:1233/system/server01/src/html/index.html). Can you imagine how hard it would be to remember an URL like that?. Fortunately, The routing method exists and will transform the full path in something that can be easily recognized by the users like https://myhairisblue.com/.
The problem with the traditional approach is the white screen displayed by the Browser while the clearing process occurs. One of the techniques used to avoid the white screen of hell is what we all know as single page application (SPA). Using this technique, the Browser will update the view without requesting a new template on the server using tools like Angular or React.
How can I navigate through my SPA without requesting a new template in the server?
The short answer is: We need to overwrite the default behavior of the server routing system.
There are two techniques to achieve this: 
  1. The hashing system — The URL protocol allows users to interact with the URL without generating a new request to the server appending #. With this method, it is possible to update the information presented to the user by changing the URL without requesting a new template. (https://myhairisblue.com/#/no-refresh-page).
  2. The redirect method — This implies to redirect all the server petitions to the index.html. With that setup in place, we can interact with the URL without the use of the hashing system. (https://myhairisblue.com/no-refresh-page).
With all of this in mind, let’s start with the code:

Coding Time

Please fork this repo to start working in the React project. The URL of the Angular tutorial is here.
Registering a route
Here we are. In Angular, you must use the tools provided by the Angular Team. It’s a very well tested solution with excellent support. However, in React, we are the kings, aren’t we?.
How could I Register a route using React?
Let’s start by checking all the different options available in the official React documentation. As you can see, there are different flavors (Aviator, Backbone, component-router, Director, Finch, Reach Router, react-mini-router, react-router, react-router-component, and so on.). On this tutorial, I’ll pick the most popular routing libraries, I’m talking about React Router Dom and Reach Router.
I picked these two libraries because according to npmtrends.com, those are the most used. Please go here to see the results yourself.
Let’s start by creating the Product Details Component
  1. Create a file
    ProductDetails.js
    Add the following code.
  2. Add the following code:
  3. import React from 'react';
    
    const ProductDetails = () => {
    
      return (
        <div className="product-deatils">
          <h2>Product Details works!</h2>
        </div>
      )
    };
    
    export default ProductDetails;
Let's code using React Router Dom
1. Go to
index.js
2. Import the
BrowserRouter
Component.
import { BrowserRouter as Router, Route } from "react-router-dom";
3. Replace
Fragment
by
Browser
4. Replace
Products
Component by
Route
<Route exact path="/" component={ProductList} />
5. Go to
ProductList.js
6. Import the
Link
component
import { Link } from "react-router-dom";
7. Add the match
prop
in line 9.
const ProductList = ({ name, match }) => {
8. Update the anchors as follows:
<Link to={`${match.url}products/${index}`} 
      title={`${product.name} details`}> 
  { product.name }
</Link>
Now is time for Reach React Router
1. Go to
index.js
2. Import the
Router
Component
import { Router } from "@reach/router"
3. Replace the
<div className="container">
container.
4. Go to
ProduList.js
5. Import the
Link
component
import { Link } from "@reach/router";
6. Update the anchors as follows:
<Link to={`/products/${index}`} 
      title={`${product.name} details`}> 
  { product.name }
</Link>
At this point, the application will be able to:
  1. Display the index page.
  2. Navigate to the Product Details Page to display the new
    ProductDetails
    Component after a click on each product title.
What did we do?
In React, everything is a Function. If the Function has some behavior related to the DOM, you will have a Component. The Router is a component too, something similar to the
<router-outlet>
we use to inject the Angular components. However, it doesn’t use a configuration object but routes specified as children components.
Another thing you will notice is the use of the
<Link>
component instead of specifying the new path using a regular anchor
<a>
. As a general rule, you should pick a
<a>
component if the intention is to link an external resource and you should use a
<Link>
component when connecting different URL within the SPA.
What does the Link component do?
The
<Link>
component will render a valid
<a>
tag, and it will prevent the default behavior  —  submit a form, open a new tab, and so on — and it maps the given props options with the final anchor returned. Please refer to the official documentation of the router component for more information.

Using route information

On this section, we will use the data of the URL to display the right information into the
ProductDetails
view.
1. Go to the
index.js
2. Import the
ProductDetails
Component.
import ProductDetails from './ProductDetails';
3. Add a route to the product detail:
// Using react-router-dom
<Route path="/products/:productId" component={ProductDetails} />

// Using reach-router
<ProductDetails path="/products/:productId" />
4. To read the param provided in the URL using React Router Dom, replace
ProductDetails.js
with:
import React from 'react';

import {products} from './products';

const ProductDetails = ({ name, match }) => {
  const { params: { productId }} = match;
  const product = products[productId];

  return (
    <div className="product-deatils">
      <h2>Product Details</h2>
      <div>
        <h3>{ product.name }</h3>
        <h4>{ product.price }</h4>
        <p>{ product.description }</p>
      </div>
    </div>
  )
};

export default ProductDetails;
5. To read the param provided in the URL using Reach Router, replace
ProductDetails.js
with:
import React from 'react';

import {products} from './products';

const ProductDetails = ({ name, productId }) => {
  const product = products[productId];

  return (
    <div className="product-deatils">
      <h2>Product Details</h2>
      <div>
        <h3>{ product.name }</h3>
        <h4>{ product.price }</h4>
        <p>{ product.description }</p>
      </div>
    </div>
  )
};

export default ProductDetails;

What did we do?

This section was about registering the routes. As an Angular developer, I have to be honest; moving from a configuration object to the composing pattern was weird. I had to stop trying to find a way to generate routes based on an object configuration (I tended to use collections to produce the required JSX). Trust me, after a couple of days working with React you will find JSX is your best friend, and you will start using functions for everything.
You won’t have to remember the keys name of the configuration object but the prop name given to the component.
Why Angular uses a subscription to inform about router changes and React doesn’t.
The Angular architecture includes a service layer in parallel to the Component system; therefore, a subscription is required to inform about changes. In React, we don’t need a subscription because using the composition pattern all the events will happen sequentially, including the rending of the new page.
At this point the app should be able to:
  1. Navigate to the product details page.
  2. Display the information of each product based on the product index present in the URL.

The currency pipe

The last section we have to cover is the use of the Currency Pipe. In React, there isn’t something like a Pipe but Functions. Do you remember?
In React, everything is a function.
In Angular terms, a pipe represents a function that allows us to edit variables directly in the template. You could create a
/pipe
folder to store all the functions that will interact with your JSX. Although, in most of the projects I’ve been working on, this kind of folder its called
/utils
. Over there, you will find all those functions that can be reusable in the app, including those that interact with the template.
To create the currency function:
  1. Go to the
    ProductDetails.js
     
  2. Add the currency function:
    const currency = number => {
      return number.toLocaleString(
        "en", 
        {
          style: "currency", 
          currency: "USD", 
          minimumFractionDigits: 2
        }
      );
    }
3. Use the function to format the price
<h4>{ currency(product.price) }</h4>

What did we do?

We created a JavaScript function using the
toLocaleString
method available in the number instance. This method allows us to create a new string with currency style. As you see, creating Pipes is not related to React, but JavaScript.
Learning how to code with React has made me a better JavaScript developer. When you start working with React, you will have to use many of the core JavaScript functionalities. Plus, you will discover more elegant and efficient ways to write code. An excellent example of this is: when I was working with Angular, I didn’t know about the
toLocaleString
method, I just used the convenient set of functions available with the framework.

Show me the code

In the following links you will find the final code:
  1. Angular.
  2. React + React Router Dom.
  3. React + React Router.

What’s next?

In the following post, we will cover how we could manage the data following the React style. I hope you find this useful to understand the concepts behind React as an Angular developer.
Thanks for reading, please support me by sharing this article or following me on Medium and Twitter or LinkedIn.
Thanks to @camiloandresAC

Written by xthecapx | Javascript Developer
Published by HackerNoon on 2019/08/31