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
Welcome to FullStack Labs. We use cookies to enable better features on our website. Cookies help us tailor content to your interests and locations and provide many other benefits of the site. For more information, please see our Cookies Policy and Privacy Policy.

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

Written by 
,
Angular to React.js - Getting Started (Part 1 of 6)
blog post background
Recent Posts
Integrating GitHub Actions and Docker for a Java Project
Businesses Must Seize the AI Wave (Or Cease to Exist)
Code, Deploy, Succeed: Next.js, Firebase, and Tailwind CSS Unleashed

Angular to React - Getting Started

Table of contents

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:

  • 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:

-- CODE language-jsx keep-markup --
<myhair color="blue">  </myhair>
    My Head

Compiled JavaScript:

-- CODE language-jsx keep-markup --
React.createElement(  
    MyHair,  
    {color: 'blue'},  
    'My Head'
)

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

-- CODE language-jsx keep-markup --
/* Functions Mode looks like: */
functionMyHair(props) {
    return<h1>My hair is, {props.color}</h1>;
}

/* Class Mode looks like: */
classMyHairextendsReact.Component {  
    render() {    
        return<h1>My hair is, {props.color}</h1>;  
    }
}

  • props: The props represent the communication channel from the parent to the children, equivalent to Angular’s @inputs.
  • props.children: Reserved prop containing the content between the opening and closing tags: <myhair>{/* props.children */}</myhair>.
  • state: Variables managed by the Component that could trigger UI updates.
  • 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:

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

-- CODE language-jsx keep-markup --
<app-top-bar></app-top-bar>/* The content of the HTML File */

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></app-top-bar> with a <div></div>:

-- CODE language-jsx keep-markup --
<div> {</div>/*The content of the HTML*/}

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">.</div>
  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>:

-- CODE language-jsx keep-markup --
{products.map(product => {  
    return (    
        <div></div>
            <h3></h3>
                <a title="{`${product.name}" details`}="">         </a>
                   { product.name }        
                
            
           
    )
})}

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

  • Go to ProductList.js
  • For the short-circuit evaluation, add the following code below the closing tag.

-- CODE language-jsx keep-markup --
{product.description &&<p>{`Description: ${product.description}`}</p>}

  • For the ternary condition use:

-- CODE language-jsx keep-markup --
{product.description ? <p>{`Description: ${product.description}`}</p> : null}

  • For the if-else statement, add the following lines

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

-- CODE language-jsx keep-markup --
<button onclick="{share}"></button>
    Share

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:

  • Add a new file: ProductAlerts.js
  • Inside ProductAlerts.js, add the following code:

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

exportdefault ProductAlerts;

  • Go to ProductList.js
  • Import the component.

-- CODE language-jsx keep-markup --
import ProductAlerts from ‘./ProductAlerts’;

  • Add the following code below the button closing tag.

-- CODE language-jsx keep-markup --
<productalerts product="{product}"></productalerts>

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.

  • Go to ProductList.js
  • Add the following code below the share() function.

-- CODE language-jsx keep-markup --
const onNotify = () => {  
    window.alert('You will be notified when the product goes on sale');
}

  • Add a new prop to the ProductAlert component and pass the reference of the onNotify function.

-- CODE language-jsx keep-markup --
<productalerts product="{product}" notify="{onNotify}"></productalerts>

  • Go to ProductAlerts.js
  • Add the new prop name to the params.

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

Written by
People having a meeting on a glass room.
Join Our Team
We are looking for developers committed to writing the best code and deploying flawless apps in a small team setting.
view careers
Desktop screens shown as slices from a top angle.
Case Studies
It's not only about results, it's also about how we helped our clients get there and achieve their goals.
view case studies
Phone with an app screen on it.
Our Playbook
Our step-by-step process for designing, developing, and maintaining exceptional custom software solutions.
VIEW OUR playbook
FullStack Labs Icon

Let's Talk!

We’d love to learn more about your project.
Engagements start at $75,000.

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