Angular to React.js - Routing (Part 2 of 6)

Written by Cristian Marquez

Welcome back to the second part of my six-part guide for Angular developers looking to learn React. Over the course of the series, we will rebuild Angular’s starter app example in React, covering each section of the Angular Starter docs in a separate article.


In the Angular developers, we reviewed the essential elements of the React template, the prop system, and the communication that takes place between parent and children components. In this article, we will discuss routing. Happy coding! :D


Routing in React vs. Routing in Angular


In general, React and Angular handle routing a bit differently.


Angular provides a routing service, but React requires developers to incorporate their own. There are a variety of React routing libraries listed in the React Documentation (you can find the list here). We will use the most popular library for this tutorial, React Router DOM.


React uses a

Router

component similar to Angular’s

<router-outlet>

, however it doesn’t use a configuration object. Instead, it specifies routes as child components.


In React, the

<Link>

component replaces the

<a>

element when connecting separate URLs within a single-page application (SPA). When linking to an external resource, you will still generally use

<a>

.


The Project



Please fork this repo to continue working on our React project. You can find the Angular tutorial we are referencing here.

Registering a Route in React


Let’s start by creating the Product Details Component. First, create a

ProductDetails.js

with the following code:



import React from 'react';

const ProductDetails = () => {
  return (
    <div className="product-deatils">
      <h2>Product Details works!</h2>
    </div>
  )
};

export default ProductDetails;
  

Let’s integrate React Router Dom. Go to the index.js and import the

BrowserRouter

Component.



import { BrowserRouter as Router, Route } from "react-router-dom";
  

Replace

Fragment

with

BrowserRouter

.



<BrowserRouter>
/* Other components  */
</BrowserRouter>
  

Then, replace

ProductList

with

Route

.



<BrowserRouter>
  <TopBar />
  <div className="container">
    <Route exact path="/" component={ProductList} />
  </div>
</BrowserRouter>
  

Next, go to

ProductList.js

and import the

Link

component. It will render a valid

<a>

element and prevent the default behavior. It will also map the given props options on to the final anchor returned.



import { Link } from "react-router-dom";
  

Add the

match

prop in line 9.



const ProductList = ({ name, match }) => {
  

Finally, replace

<a>

with the following:



<Link to={`${match.url}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 when a product title is selected.

Using Route Information


In this section, we will pull the product details from the URL and pass it to the

ProductDetails

component. This will allow the

ProductDetails

component to display a product when it is selected from the ProductList page.


Go to the index.js and import the

ProductDetails

component.


import ProductDetails from './ProductDetails';
  

Add a route for the product detail page:


<Route path="/products/:productId" component={ProductDetails} />
  

To read the param provided in the URL, replace the contents of

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;
  

At this point the app should be able to display the product details on a product page. However, the product price will be missing a currency indicator. Angular uses a currency pipe to format a number into a monetary value. Pipes are essentially functions, so we can simply create a function to replicate Angular’s Currency Pipe.


To create the currency function, we need to use the built-in Number method

toLocaleString

. Start by adding the currency function to the ProductDetails.js file.


const currency = number => {
  return number.toLocaleString(
    "en", 
    {
      style: "currency", 
      currency: "USD", 
      minimumFractionDigits: 2
    }
  );
}
  

Then, use the function to format the price.


<h4>{ currency(product.price) }</h4>
  

Solutions

  • The Angular solution to this tutorial can be found here.
  • The React solution to this tutorial can be found here.

Learning how to code with React has made me a better Javascript developer. When you start working with React, you have to use many of Javascript’s core functionalities. You will also discover more elegant and efficient ways to write code.


In the next post, we will cover data management. I hope you found this tutorial useful for understanding routing in React!


---
At FullStack Labs, we pride ourselves on our ability to push the capabilities of cutting-edge frameworks like React. Interested in learning more about speeding up development time on your next project? Contact us.

Let’s Talk!

We’d love to learn more about your project. Contact us below for a free consultation with our CEO.
Projects Start at $25,000.

FullStack Labs
This field is required
This field is required
Type of project
Reason for contact:
How did you hear about us? This field is required