Angular is a framework that I have the most experience with, and while I still love it, I cannot deny react’s popularity. Therefore, I thought it would be a good time to explore react and maybe try to understand what makes it so special. In this post, I will talk about building a react app for Java backend e.g. to show news articles that it gets from a Java spring-boot powered REST API.

Background

In the last 4-5 years, React has gained a lot of popularity in the Australian market. I have seen one too many ads on the Australian job sites for react engineers. It’s a very big thing right now. To my surprise, even at my old job, where I learned AngularJS 1.0, they switched to React. Being someone who started off with Angular 1 and moved to Angular 2+, I found myself thinking, wait, what just happened? React just came in from nowhere and took over most of the market? It must clearly offer some benefits over Angular. Hence, I thought it would be a good time to give React another look. I think it would help if I added some context into the problem we are solving with the react app we will built here.

The first time I ever used react was, to do one of the so called “tech tests” for a job interview last year. You can have a look at that Github repository over here. The job ad was for “Javascript engineer”, but their feedback pointed to react specific things missing from my code, they wanted a react engineer!

cptdanko/react-au-postcode-validator (github.com)

The problem

The task is to display a list of articles that we retrieve from this REST API. Each article has an id, name, title, body and tags. The layout should show the image on the far left, followed by the title on right, the body and tags below it. The goal is to simply build a proof of concept app in whatever tech we are comfortable with. If approved, then the implementation can be in whichever technology the team is most comfortable with.

Solution: React app for Java

The problem itself is quite simple isn’t it? I mean, we can call it a standard “cookie-cutter” problem. Any front-end engineer can solve it with little or no difficulty. It almost makes you think, so why even bother with such a simple problem! Yes, the problem is indeed simple but we will be building a fully working app and once approved what if we need to change that to use Angular, Vue.js or whichever Javascript framework is the next big thing by next week? In that case it would be awesome if we can save some time by reusing code from parts of this solution. Therefore, the key here would be to think about and isolate aspects of this solution that can be reused in a different framework.

Getting started with react

This is one of the simplest things that can be done, yet….. I had an issue with that too? As the react tutorial suggests, I ran the following commands

npx create-react-app my-app
cd my-app
npm start

I was working on my ubuntu 18.04 machine and the app would not start on npm start. It was so confusing? I thought to myself, I am probably the worst engineer ever!!! I mean, generating a project with CLI and running that code is perhaps the simplest thing you can do. Yet here I was looking for a solution to do just that. Anyway, it didn’t take me too long to solve the issue by saving a .env file with the following key.

SKIP_PREFLIGHT_CHECK=true 

Remember, I only needed this for my machine running Linux Ubuntu. Had this taken me anything more than 10-30 minutes, it was time to jump off a cliff an put an end to this unfulfilling existence. That is the most logical course of action if it takes me that long after years of experience. Either that or at least give the idea a serious thought over a warm cup of tea (sarcasm, dark humor).

Article – (Components)

For now, we would show articles on the home page, but in the future we may need to show them on other pages too. So it would make sense keep all the code to capture, style and display articles as something we can just drop into any page and have it just work. We can achieve that in react via components.

Ok let’s pause there, right now we know we will have a react app that shows articles, with images and maybe a button to reload (refresh) articles. It’s safe to say, we have an idea of what our react app would look like, so let’s write a few simple tests before moving forward.

App.test.js

import React from 'react';
import { render, screen } from '@testing-library/react';
import App from './App';
import Article from './components/article';

describe("Test App.js" , () => {
  test('should render learn react link', () => {
    render(<App />);
    const linkElement = screen.getByText(/News/i);
    expect(linkElement).toBeInTheDocument();
  });  
});

describe('Articles rendered', () => {
  test('should render article image', () => {
    render(<App />);
    render(<Article />);
    expect(screen.getByAltText(/logo/i)).toBeInTheDocument();
  });

  test('should render article', async () => {
    render(<Article />);
    const text = await screen.getByText(/Articles/i);
    expect(text).toBeInTheDocument();
  });

  test('should have a refresh button', async () => {
    render(<Article />);
    const refreshBtn = await screen.getByRole('button');
    expect(refreshBtn).toBeInTheDocument();
  });
})

Great we have tests now, even though the will fail at this stage, but good to have them ready. Now, let’s see what an article component would looks like, by first looking at the css file.

Article.css

.Articles {
    list-style-type: none;
    padding-left: 8px;
    padding-right: 8px;
}

.Article {
    padding-bottom: 8px;
    display: flex;
    margin-top: 10px;
    padding: 10px;
    border-bottom: 3px solid darkkhaki;
}
.Article .Story {
    flex-direction: column;
    justify-content: flex-start;
    padding-left: 15px;
}
.Article .Story .Title {
    font-size: 24px;
    font-weight: bolder;
    margin-top: 0;
}
.Article .Story .Tag {
    padding-bottom: 10px;
    color: darkcyan;
}
.Article-Img {
    max-width: 150px;
    max-height: 150px;
}

Followed by Article.js

import React from "react";
import axios from "axios";
import "../styles/Article.css";
import priceline from "../images/priceline.jpeg";
import longbottom from "../images/longbottom.jpg";
import lockdownpay from "../images/lockdownpay.jpeg";

function Articles() {
  const [articles, setArticles] = React.useState([]);

  React.useEffect(() => {
    axios
      .get("/all", { crossDomain: true })
      .then((response) => setArticles(response.data));
  }, []);

  function imgToDisplay(idx) {
    switch (idx) {
      case 0:
        return priceline;
      case 1:
        return longbottom;
      default:
        return lockdownpay;
    }
  }

  return (
    <div>
      <ul className="Articles">
        {articles.map((article, idx) => (
          <div className="Article" key={article.id}>
            <div>
              <img src={imgToDisplay(idx)} className="Article-Img" alt="logo" />
            </div>
            <div className="Story">
              <li key={article.id}>
                <span className="Title">{article.title}</span>
                <p> {article.body} </p>
                <span>
                  {" "}
                  Tags [{" "}
                  <span className="Tag">
                    {article.tags.replace(/,/g, " - ")}
                  </span>
                  ]{" "}
                </span>
              </li>
            </div>
          </div>
        ))}
      </ul>
    </div>
  );
}
export default Articles;

Don’t worry about the hard-coded images for now. To use the article component in a file in our react app, we can simply include it in App.js that was generated during create-react-app.

import logo from './logo.svg';
import './App.css';
import Articles from './components/article';

function App() {
  return (
    <div className="App">
      <header className="App-header">
        <img src={logo} className="App-logo" alt="logo" />
        <span className="Title">News</span>
      </header>
      <Articles />
    </div>
  );
}

export default App;

App.css

.App {
  max-width: 50%;
  margin: auto;
}

.App-logo {
  height: 10vmin;
  pointer-events: none;
}

@media (prefers-reduced-motion: no-preference) {
  .App-logo {
    animation: App-logo-spin infinite 20s linear;
  }
}

.Title {
  font-size: 36px;
  font-family: Verdana, Geneva, Tahoma, sans-serif;
  font-weight: bolder;
}
.App-header {
  background-color: #282c34;
  min-height: 15vh;
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  font-size: calc(10px + 2vmin);
  color: white;
}

.App-link {
  color: #61dafb;
}

@keyframes App-logo-spin {
  from {
    transform: rotate(0deg);
  }
  to {
    transform: rotate(360deg);
  }
}

@media screen and (max-width: 768px) {

  .App {
    max-width: 100%;
    margin: auto;
  }
}

And that’s pretty much it? we have our react app. If you need to more about the ins and outs of react app, maybe start by looking at the official docs.

From an Angular perspective

I have talked about directives in Angular before where a component is a type of directive that has it’s own template and a style file. You can read that post here: Building a reusable Angular component to upload images – (mydaytodo.com)

React components are not that different, they are similar in what they offer. In summary, they are reusable pieces of UI that have their own html, CSS and Javascript code that can be added to whichever page needs them.

So if we were to migrate this to an Angular app, we can reuse the existing css here and also reuse the logic from Javascript functions.

Source code

All the source code for this app can be found here on Github.

cptdanko/articlesFrontEnd: A react based frontend for the Articles API backend (github.com)

The reason why, this app is in a folder called react is that at some point, an Angular based solution can be added too. I think we have seen enough code to know we have a working react app, now let’s try compare Angular and React.

Get updates?

Angular vs React

I realise there are a ton of articles out there that talk about this, but I still think I should shed some light on my perspective on it. So what do I think about it?

Angular, the good

  1. I already know it so I am more comfortable with it
  2. Enforces a structure to follow best practices
  3. Static typing and type safety enforced via Typescript
  4. And much more, that are beyond the scope of this post

Angular, the not so good

  1. Comparatively heavy weight (size, kb)
  2. Dependency Injection can intimidate beginners, leading to,
  3. Steep learning curve and,
  4. Longer turnaround time for a task

React, the good

  1. Easy to get started with
  2. Comparatively lightweight (size, kb)
  3. Smooth learning curve
  4. Fast turnaround time for a task
  5. And much more, that are beyond the scope of this post

I do not know react as well to know what’s not so good about it. A simple Google or Bing search on React vs Angular would get you more informative articles on the topic.

My opinion

I still love Angular and I like how it mandates the use of static typing via Typescript. I like dependency injection and how code is organised in an Angular app. There’s some really good separation of concerns on display there.

However, I cannot deny the easy pickup and play nature of react. React almost gets rid of the steep learning curve of Angular and provides a relatively smooth learning experience. Also, the fact that you can see the results of your work much faster with React makes it appealing to beginners.

Best use of React?

When is it best to use react? It depends on several factors, mainly the project and the team. If I am working with a team of junior front-end engineers on a greenfield project, I would prefer using React. Why? If they do not already know React, picking up React would be much easier for them, then trying to understand dependency injection. React would ensure, they see the results of their work much faster. I realise it can be frustrating for an engineer to spend days trying to understand something without seeing a result of your work (this was me, 7 years ago, when I started on Angular). Things will just move faster with react, however some may question the long-term maintainability when compared to Angular. However that’s a topic for another post.

One other factor, market availability of engineers. Either engineers leave or more engineers need to be added as the project grows. In this case, the ease of finding engineers with relevant experience should be considered when choosing a framework.

Best use of Angular?

If I am working with a team of awesome engineers like me who come from a Java Spring background, then I would use Angular. “OHH HELL YEAH Wooohhuuuuu, Angular … Dependency Injection 4 lyf baby 🤟🏾” I should totally get a T-Shirt that says that 🙂

Ok in all seriousness, I would consider using Angular, when I intend to build a large complex application for internal organisation use. Where I know the app is going to get more complex with time with more and more features added to it over the next few years. I know for sure, that it’s easier to find React engineers here in Sydney (Australia) compared to Angular so market availability may pose a challenge long term maintainability.

Conclusion

I got a little carried away there in the end when talking about Angular. However, I love working with Angular, I struggled for almost a month when I first started on it, 7 years ago. However once I got it, I found it incredibly rewarding to work with it, but….

React is here to stay. React is a framework with which you can get started quite easily, yet it would take time to master it. I have only touched on a few basic concepts in this post, there are advanced topics such as React hooks, Routing etc etc.

Anyway, once again the source code for the Spring Boot app

cptdanko/ArticlesAPI: A Spring-boot REST backend

Source code for the react app

cptdanko/articlesFrontEnd: A react based frontend for the Articles API backend (github.com)

Get updates?

If you find any of my posts useful and want to support me, you can buy me a coffee :)

https://www.buymeacoffee.com/bhumansoni

Or you can  buying or even try one of my apps on the App Store. 

https://mydaytodo.com/apps/

In addition the above, have a look at a few of the other posts,
How to create radio buttons using vanilla Javascript
https://mydaytodo.com/vanilla-javascript-create-radio-buttons/

How to build a Javascript frontend for Java Spring Boot backend 
https://mydaytodo.com/java-spring-boot-vanilla-javascript-solution/

Or have a look at some useful Javascript tutorials below
https://mydaytodo.com/category/javascript/

Some other posts on react

Additionally you can checkout some of my other posts on reactjs.

Covid case numbers React app

The goal is to build something quick (in a day) so that it can be used ASAP. At this stage we won’t be building anything more than an online portal to track our daily case numbers predictions. We will build something that’s accessible over a browser that people can use to enter their daily predictions.

Design or layout

The (web) app will have only 1 screen with a form for the user to enter their daily prediction and a list to show other entries for the day. Given the nature of this fun project, let’s not plan too much and start building a react app with this.

You can read the full post in the link below.

https://mydaytodo.com/covid-cases-react-app/


0 Comments

Leave a Reply

Avatar placeholder