XenonStack Recommends

Data Visualization

Learn React | Advanced Guide for Angular Developers

Navdeep Singh Gill | 09 September 2021

React Learning Guide for Angular Developers

Introduction to React learning

Nowadays we know that Angular and React are on the boom for front-end developers. As both are different, one is a framework, and the other is a library which we can choose based on our needs and requirements. So, This blog is dedicated to all the Angular developers out there who are now moving on to React or the one who wants hands-on experience on React.

As we know that the learning framework is a bit hard as compared to the library. So, as said, the learning of React is also not going to be difficult for developers like us(moving from Angular to React). Also, I will not focus on the comparison between Angular and React and will focus on the learning path of React.

Before starting the guide, I would like to share my experience about the difficulties I faced when working with React. In Angular, while debugging, we can easily see the component names on chrome developer tools and fix that. But in React, we can't find the component names and have difficulty finding the component. But here, chrome comes to resume and provides an extension that can show us the component hierarchy and many more things, which can help us debug the react applications.

A web framework is an architecture containing tools, libraries, and functionalities suitable to build and maintain massive web projects using a fast and efficient approach. Complete Introduction to Python Flask Framework

What is React?

React is a javascript library for building declarative, efficient, and interactive user interfaces. With React, we can build simple to complex UI using isolated pieces of code called Components. It was created by Jordan Walke (Software Engineer at Facebook).

React is widely supported by the Facebook community.

  • SPA (Single Page Application):- As Angular, React also SPA architecture.
    Single-page applications are the web apps or the websites that load the page without reloading the whole page from the server, as in the traditional application using simple HTML, CSS, and javascript.
  • Virtual DOM:- React uses Virtual DOM (Document Object Model) to update the UI. React keeps the representation of the real DOM in the memory, and that is known as Virtual DOM. Updating the Real DOM is much slower than Virtual DOM. Whenever any state changes in the UI, the VDOM changes only that object in the real DOM. This process is called Reconciliation.

Fig:- Virtual DOM working
This is also one of the reasons why React is much faster than other Frontend frameworks.

Learning React with Angular Experience

Let's start by scratch and create the boilerplate for the application. So, Angular provides us the powerful tool called CLI (command line interface), using that we can have our basic application ready with the command 'ng new angular-project,' which gives us different files for routing, the styling of components, templates, views(using .html file), and testing file(.spec.ts) everything setup. It also provides many npm libraries installed all ready for use.

And if we want to create a new component, then also we need to use a command ng g c XYZ, and it will give us all the files ready to use, and we need to define the path for the component in the routing file.

On the other hand, for react projects, we use ​​npx create-react-app, which also gives us the basic folder structure ready, but we need to set up the files for routing, styling, and everything. Also, we need to install NPM packages manually, like react-router-dom for routing, testing packages, etc. The react application files can be .tsx(in typescript) or .jsx(in javascript) . It supports both.

In-Built Files

As we create the Angular application, we get the files created as package.json, main.ts, angular.json, polyfill.ts, and other files, configuring and compiling the application.

On the other hand, it doesn't bother us with these many files after creating the react application. It has a package.json file used for the application's configuration for setting up the environments and running the application, which is the same as Angular, and that's it.

The Src folder creates the index.js file used for bootstrapping the application using the App.js file, which is also imported in this file. Index.css file is used for the app styling App.test.ts file to set up the application's testing environment.

File Structure

In Angular, there are different files for HTML, CSS, and javascript. On the other hand, we can maintain only one file for the CSS, HTML, and javascript code.

Also, In Angular, it is about the structure of modules and components, but in React, it is all about components. So, we only need to modularize ours react application. So, with Enough theoretical knowledge, let's start with the basics of React.

Galen Framework has its special language Galen Specs for describing the positioning and alignment of elements on a Web page. Responsive Design Testing with Galen Framework

What are the Basics of React?

In React, Everything is a component. Like for styling, doing business logic, it all resides inside the component.

There are two ways of defining components in React.

  1. Functional Components
  2. Class Components.

Functional Components

Functional Components are the Javascript functions that return the HTML element to render. It accepts props for data binding between components.
E.g.:-


function App() {
const text = 'Hello World';

return (
<div className="App">
<p> {text} </p>
</div>
);
}

Class Components

Class components are a bit complex compared to functional components, as it includes constructor methods and renders () functions that return the HTML element. It looks like:-

Import React, { Component} from ‘react’;

Class ExampleComponent extends Components {

render() {

return(

<div>This is an example component.</div>);

}

}

The difference between them is that functional components use hooks for everything, like connecting the store to the app or its lifecycle methods.
On the other hand, Class components have a constructor and use props and other properties or methods for connecting to the store.

The declaration of the functional components and class components has almost become similar. Like all the features defined in the class, components can be done using functional components.
So, It depends on our choice to pick one.

LifeCycle methods of React

As in Angular, a component goes through different stages when the Angular instantiates the components and renders the component along with its child views.
The same goes for React. It also has various lifecycle methods.

For Functional Components, we have a useful effect hook used conditionally for different stages of the component.

  • useEffect(on Start):- This hook needs to be imported from React, and it executes as the component renders, same as ngOnInit.
    We can use this hook for implementing any method or making an api call that we want to get called on component render.

React.useEffect(() => {
getCountryCode();
//Function which we want to call on page on load.
}, [])

It takes two parameters, the first is a function, and the second is a dependency variable. We can pass the empty brackets if we want to execute the function only once on page load.

In class components, the same can be done using the ComponentDidMount() method.

  • Effect (on update):- When we want to update the component state, when data changes, we can use the use effect() hook with a dependency variable in square brackets, which we are supposed to change with the state.

React.useEffect(() => {
getCompanyReview()

}, [company])

The function will automatically execute when the company variable changes the data, and the component gets updated.
In Class-based components, we use ComponentDidUpdate(), which runs when the state changes on the component.
It is the same as ngOnChanges() in Angular.

  • useEffect(on destroy):- When we want to do the clean up the component, we can pass an empty array on the useEffect as:-

useEffect(() => {
return () => {
console.log("cleaned up");
};
}, []);

In Class-based components, we use the ComponentWillUnmount() hook to execute before the component gets destroyed.
It is the same as ngOnDestroy(), which gets called before the component gets destroyed.

Website security is not a simple task, and to secure websites and application then the security comprises of a lot of factors that go into web security and web protection. Website Security - Benefits | Tools | Measures

Passing data between Components

In Angular, we have @Input and @Output decorators for passing the data between child and parent components.

In React, we have props to pass the data from parent to child components in functional components.

Props:- Props are the object or the properties which we pass to the component to render.

function User(props) {
return <h1>Hello, {props.name}</h1>;
}
function App() {
return (
<div>

<User name="Sara" />
</div>
);
}
ReactDOM.render(
<App />,
document.getElementById('root')
)

In the above example, the name is passed as a props with the User component.

States:- States in react keep track of the variable changes or any input data changes which drive the component to re-render. The state is also the same as props which hold the object in the component.

Class Timer extends React. Component {

constructor(props) {
super(props);
this.state = { date: new Date() };
}

render() {
return (
<div>
<h1>Hello, world!</h1>

<h2>It is {this.state.date.toLocaleTimeString()}.</h2>
</div>
);
}
}

ReactDOM.render(

<Timer />,
document.getElementById('root')
)

Another example of props in react.

function AvailableMeals() {
return (

<MealItem key={meal.id} name={meal.name} description={meal.description} />

//we are passing the meal name and description to the MealItem component, which can be received using props as
)

};


function Mealtem(props) {
return (
<div>
<h3 >{props.name}</h3>
<div className={classes.description}>{props.description}</div>
</div>
)
}

This is only used when we want to pass our data from parent to child. But, what if we're going to change the child component and want it to get reflected in the parent component (as @output decorator) does for us.

In React, we can use callback functions. Through props, we can pass the functions and use that to change the data in the parent component.

E.g.:-

<MealItemForm id={props.id} onAddToCart={addToCartHandler}/>

In the parent component, we can implement the function addToCartHandler, which will listen for the change and updates the value (this can be done using useState()) in react or something like this:-

const addToCartHandler = amount => {
cartContx.addItem({
id: props.id,
name: props.name,
amount: amount,
price: props.price
})
}

In the child component, we can receive the function using props and do the change as:-

props.onAddToCart(enteredAmountNumber);

So, now it will listen for the change in the entered amount.

TDD is nothing but the development of tests before adding a feature in code. This approach is based on the principle that we should write small codes.Test and Behavior Driven Development

Iteration

In Angular, we have structural directives like *ngFor, which is used for iterating the elements or components.

In React, we can iterate elements or components using a map or for javascript method. In React, everything is pure javascript. We can use native javascript methods to execute the function. Assigning a component to a variable is still valid.

const mealsList = meals.map(meal => <MealItem key={meal.id} name={meal.name} description={meal.description} />)
//Then use the mealsList in the component as:-

function AvailableMeals() {
Return (
<ul>{mealsList}</ul>
)
}

Conditional Rendering

In Angular, we have a structural directive as *ngIf, which we can use for conditionally rendering the components or elements.

In React, we can use if condition as in javascript to do the conditional rendering.
As:-

{isCheckout && <Checkout onConfirm={submitOrderHandler} onCancel={props.onClose} />}

Here, if the isCheckout is true, it will render the Checkout component.

We can also use the syntax:-

{isCheckout ? (
<Checkout onConfirm={submitOrderHandler} onCancel={props.onClose} />
) : (
<Empty></Empty>
) }

The thing is, all javascript syntax is valid to use.

Structural Directives(ng-templates and ng-container)

In angular, we use the above directives, which render the elements until the condition is true.

In React, there are no such directives. Instead, we use React. Fragments to wrap the container in the component which is represented as:-

function MyComponent() {

return (
//react fragments.
<>
</>
}
}

HTTP Requests in React

In Angular, we have services where we make the api calls using HTTP the client provided by Angular.

But in React, there is no such dependency. We can make api calls using the simple javascript method fetch or use npm packages like Axios and request.

Store in React:-

As in Angular, we can use libraries like the ngrx store to set up the application's state management.

In React, there are many libraries like redux-saga, redux-thunk, react-redux, which we can use for the state management in the application.

The functionality is almost the same in react. It also contains reducers, actions, and selectors.

The effects in ngrx-store vary with the library we choose.

The concept of Stateful and Stateless Applications is the foundation upon which most architectures and designs are based upon — concepts like RESTful design are built on these foundations.Stateful and Stateless Applications Best Practices

Setting Routes in React

To set Routes in React, we need to install the package react-router-dom. Then we can import a few modules from the package. We need a browser router, Route, and Switch for setting the basic routing for our application.

We can rename the browser router as Router (just for convenience). It is used to wrap our App component and provide our application routing functionality.
We need a Route component to return with the properties path and component specified, redirecting our page.

We need to wrap the Route component inside the Switch component, so only one component renders simultaneously.

We can also add the exact keyword to ensure that it only renders the component when it matches the exact path.

Fig:- Setting up Route in React

Things not present in React

Few things are not present in the React like:-

  1. Pipes:- There are no pipes. We need to use our methods or the packages present to transform our data. Like for transforming the data into our desired format, we can use the in-built Date method current in javascript to format it or we can use moment.js
  2. Dependency Injection:- In Angular, we have a design pattern Dependency Injection, but in React, we don't have.
  3. Setting up Routes:- As in Angular, we automatically get an app.routing.ts file created for routing. But in React, we need to create it explicitly and install the react-router-dom or any other npm package for it. We only need to define the modules, components and set up everything from scratch in react.

Conclusion

Both React and Angular are growing at their own pace. Learning React after Angular is not much harder as compared to learning Angular after React.
In React, after knowing a few basic concepts, we are good to work with the react projects because it contains pure javascript.

Summarising all the above points in one diagram:-