Angular to React.js - Getting Started (Part 1 of 6)

Written by Cristian Marquez

Angular to React - Getting Started


I recently built my first few React apps after years of working with Angular. Making the switch from Angular to React requires a mindset change that can be difficult and time consuming. These frameworks take fundamentally different approaches to frontend development. For example, Angular offers a complete ecosystem, while React requires integration with external libraries to provide similar functionality.


Below is the first article of a six-part guide to help ease the transition from Angular to 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. These articles will cover set up, routing, managing data, forms, and deployment. Happy coding! :D


Code structure


Angular has a defined code structure, as components are broken into separate templates, styles, and JavaScript files. The template uses HTML, the styles use CSS/SCSS/SASS, and the JavaScript file uses Typescript. This structure allows backend developers to generate users interfaces with code that is familiar to them.


In React, on the other hand, allows developers full freedom to define the structure of their projects. They can combine the templates, styles and business logic into a single Javascript file, separate each into different files, or set an entirely new structure.


Key Terms


To refresh your Angular vocabulary, take a quick look at the glossary here. Below are some key React.js terms you’ll need to know to get started:


  1. JSX: The React template system that resembles HTML. Babel will compile JSX to regular ES6 Javascript. Go here for a basic introduction or go to the official documentation to find a complete tutorial.

    JSX:


    <MyHair color="blue">
      My Head
    </MyHair>
    

    Compiled JavaScript:


    React.createElement(
      MyHair,
      {color: 'blue'},
      'My Head'
    )
    

  2. Elements: Code that represents what you want to see on the screen: const element = <h1>Hello, world </h1>.
  3. Components: Functions/classes that define the behavior of elements.

    // Functions Mode looks like:
    function MyHair(props) {
      return <h1>My hair is, {props.color}</h1>;
    }
    
    // Class Mode looks like:
    class MyHair extends React.Component {
      render() {
        return <h1>My hair is, {props.color}</h1>;
      }
    }
    
  4. props: The props represent the communication channel from the parent to the children, equivalent to Angular’s @inputs.
  5. props.children: Reserved prop containing the content between the opening and closing tags: <myHair>{/* props.children */}</myHair>.
  6. state: Variables managed by the Component that could trigger UI updates.
  7. Events: Functions executed by the Components. React Events could be associated with HTML Events.


Project Setup


For this tutorial, we will be rebuilding Angular’s official starter store app using React. Follow the starter app instructions for generating a repo with StackBlitz, then go here and fork the project.


With the initial configuration, the app should look like:


Starter state for React tutorial

Angular to React Syntax

Our first step is to translate Angular HTML syntax to React JSX syntax. In Angular, components are generated with @Component:


@Component({
  selector: 'app-top-bar'
})

Angular automatically creates a wrapping HTML element using the value of selector. In this case the wrapping HTML element will look like this:


<app-top-bar><!-- The content of the HTML File --></app-top-bar>

Creating components in React is slightly different for two reasons. One, React simply returns JSX without creating any extra wrapper elements. Second, the Angular HTML syntax is not valid JSX and will throw an error. Therefore, we will need to rewrite this component to work with React. To accomplish this we can simply replace <app-top-bar> with a <div>:


<div> {/*The content of the HTML*/}</div>

Although we now have a valid JSX component, the styles in `style.css` are no longer being applied to the element. To fix this we need to add a CSS class to our element. In React, CSS classes are added to elements using the className prop rather than the normal HTML class attribute. You can read more about styling in React here.


Follow the steps below to update our Angular component to a React Component using what we learned above:


  1. Go to TopBar.js
  2. Ensure the parent element to be: <div className="app-top-bar">.
  3. Go to style.css, replace app-top-bar with .app-top-bar.
  4. Remove the router-outlet + * selector and add the padding to the .container.


At this point, the app should look like:



Iterating over the list


In React, there are no specific directives to iterate in JSX, we can simply iterate using JavaScript. To render the products in the ProductList component, do the following steps:


  1. Go to ProductList.js
  2. Add the following code below <h2>Products</h2>:
    {products.map(product => {
      return (
        <div>
          <h3>
            <a title={`${product.name} details`}>
              { product.name }
            </a>
          </h3>
        </div>
      )
    })}
    

    With those changes in place, the app should look like:


Remember, everything in React is JavaScript. The information about products is present in the products variable. Therefore, we can use the Array.map to generate the required JSX code.


Notice the anchor element takes a “title” prop which is defined using curly braces. This allows JSX to execute a JavaScript expression. In this example, we are generating the title using the literal string.


Conditional rendering


To conditionally render an element in React, we should use one of the following options: 1) An if else statement, 2) A ternary conditional or 3) Use the short-circuit evaluation technique


  1. Go to ProductList.js
  2. For the short-circuit evaluation, add the following code below the </h3> closing tag.
    {product.description && <p>{`Description: ${product.description}`}</p>}
  3. For the ternary condition use:
    {product.description ? <p>{`Description: ${product.description}`}</p> : null}
  4. For the if-else statement, add the following lines

    // in the function body
    let description;
    if (product.description) {
     description = <p>{`Description: ${product.description}`}</p>
    }
    // Bellow the h3 closing tag
    {description}
    


The app should look like:


App with description and conditional rendering

HTML event listener


With JSX, developers will have access to the HTML events directly in the element. To execute the function share() after clicking a Button, do the following:


  1. Go to ProductList.js
  2. Bellow the Product description element, add the following.
    <button onClick={share}>
    Share
    </button>


After click in the Button, the app looks like this:



Creating a Component


The component system in React consists of functions that return the required JSX code. The params of the function are the props received by the component, and the template is the JSX returned statement. To generate a new React element, do the following:


  1. Add a new file: ProductAlerts.js
  2. Inside ProductAlerts.js, add the following code:
    import React from 'react';
    import {products} from './products';
    
    const ProductAlerts = ({ product }) => {
      let productAlerts;
      
      if (product.price > 700) {
        productAlerts = <p><button>Notify Me</button></p>;
      }
      
      return <div className="product-alerts">{productAlerts}</div>
    };
    
    export default ProductAlerts;
  3. Go to ProductList.js
  4. Import the component.
    import ProductAlerts from ‘./ProductAlerts’;
  5. Add the following code below the button closing tag.

    <ProductAlerts product={product} />


The app should look like:


App with children notification component

We are generating a new React component. A React component is a JavaScript file that imports React and exports a function which returns JSX code. In the ProductList file, we are providing the prop product. It allows us to use that variable inside the ProductsAlerts through the params of the function.


The React “Output”


Let’s start this section saying that output concept of Angular doesn’t exist in React. The communication between components occurs in one way. However, it is possible to execute a method of the parent component providing a reference of the method to the child component.


  1. Go to ProductList.js
  2. Add the following code below the share() function.
    const onNotify = () => {
      window.alert('You will be notified when the product goes on sale');
    }
  3. Add a new prop to the ProductAlert component and pass the reference of the onNotify function.
    <ProductAlerts product={product} notify={onNotify} />
  4. Go to ProductAlerts.js
  5. Add the new prop name to the params.
    const ProductAlerts = ({ product, notify }) => {
      // Attach the click event, providing the prop received into the onClick prop of the Button. 
      <button onClick={notify}>Notify Me</button>


Now, if you click in the notify button the app should looks like:


Notification system message

In JavaScript, when we reassign a function into a variable, we are not creating a new instance of the function but a reference. Hence, if we execute notify() inside the ProductAlerts component, the onNotify function is executed.


The Result

  • The Angular code to this tutorial can be found here
  • The React code to this tutorial can be found here


What’s next?


I hope you find this information useful for your transition to React. In the next part of this six-part series, we will continue to use the starter project above to learn more about 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