FullStack Labs

Please Upgrade Your Browser.

Unfortunately, Internet Explorer is an outdated browser and we do not currently support it. To have the best browsing experience, please upgrade to Microsoft Edge, Google Chrome or Safari.
Upgrade

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

Written by 
Cristian Marquez
,
Senior Software Engineer
Angular to React.js - Routing (Part 2 of 6)
blog post background
Debugging in React Native: Flipper vs React Native Debugger vs Reactotron
Agile Test Management - Zephyr for JIRA
The Difference Between MongoDB and Firestore, and When You Should Use Each

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 previous article, 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:

-- CODE language-jsx keep-markup --
import React from 'react';
const ProductDetails = () => {  
    return (    
        <div className="product-deatils">
            <h2>Product Details works!</h2>
        </div>  
    )
};

exportdefault ProductDetails;

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

-- CODE language-jsx keep-markup --
import { BrowserRouter as Router, Route } from "react-router-dom";

Replace Fragment with BrowserRouter.

-- CODE language-jsx keep-markup --
<BrowserRouter>
    /* Other components  */
</BrowserRouter>

Then, replace ProductList with Route.

-- CODE language-jsx keep-markup --
<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.

-- CODE language-jsx keep-markup --
import { Link } from "react-router-dom";

Add the match prop in line 9.

-- CODE language-jsx keep-markup --
const ProductList = ({ name, match }) => {

Finally, replace <a> with the following:

-- CODE language-jsx keep-markup --
<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.

-- CODE language-jsx keep-markup --
import ProductDetails from './ProductDetails';

Add a route for the product detail page:

-- CODE language-jsx keep-markup --
<Route path="/products/:productId" component={ProductDetails} />

To read the param provided in the URL, replace the contents of ProductDetails.js with:

-- CODE language-jsx keep-markup --
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>  
    )
};

exportdefault 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.

-- CODE language-jsx keep-markup --
const currency = number => {  
    return number.toLocaleString(    
        "en",    
        {      
            style: "currency",      
            currency: "USD",      
            minimumFractionDigits: 2    
         }  
     );
}

Then, use the function to format the price.

-- CODE language-jsx keep-markup --
<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.

Cristian Marquez
Written by
Cristian Marquez
Cristian Marquez

As a Senior Front-End developer at FullStack Labs I focus on building single page web applications using Angular and React.js. I pride myself on my attention to detail, and my ability to build pixel-perfect user interfaces. Prior to FullStack I held a variety of roles at leading Colombian companies, including Globant and Prodigious. I have a Masters of Sciences Degree in Engineering from the Universidad Nacional de Colombia.

FullStack Labs Icon

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 $50,000.

company name
name
email
phone
Type of project
Reason for contact
How did you hear about us?
Thank you! Your submission has been received!
Oops! Something went wrong while submitting the form.