Site Loader

Share with your friends!

It is been sometime after my last article. Meanwhile, I tried something interested in Front-end technologies. As we all know nowadays React, Angular and VueJS are the most trending topics in Front-end Development. Well… I agree they’re a few more and Svelte is also there. in this article, I picked only above three technologies and tried writing a small application; a prime number checker. The behaviour of the application is when a user types a number and then click the check button the result message saying whether it is a prime number or not.

I haven’t thought much about special features like Component Destructuring only focused on the ground-level implementation of these technologies. I have used the same style file in all the implementations.

The preview of the application

React

Let’s check the implementation of React. If you are interested in Demo, please find it here.

import React, { useState } from "react";
import "./styles.css";

export default function App() {
  const [value, setValue] = useState("");
  const [result, setResult] = useState("");

  const handleChange = e => {
    setValue(e.target.value);
    setResult("");
  }

  const isPrime = num => {
    for(let i = 2; i < num; i++)
      if(num % i === 0) return false;
    return num > 1;
  }

  const handleClick = _ => {
    if (isNaN(value)) {
      setResult("ERROR");
    } else {
      const res = isPrime(parseInt(value, 10)) ? "YES": "NO";
      setResult(res);
    }
  }

  let text = "";
  let classValue = "";

  if (result === "YES") {
    text = `${value} is a prime number`;
    classValue = "success panel";
  } else if (result === "NO") {
    text = `${value} is not a prime number`;
    classValue="error panel";
  } else if (result === "ERROR") {
    text = `${value} is not a number`;
    classValue="error panel";
  }

  return (
    <div className="App">
      <div>
        <p>Enter number to verify prime number</p>
        <input type="text" className="input" value={ value } onChange={ handleChange }/>
      </div>
      <div>
        <button className="button" onClick={ handleClick }>Check</button>
      </div>
      <div className={ classValue }>{ text }</div>
    </div>
  );
}

This React code only took one file since it used JSX. The reactive mechanism in React helped to achieve this kind of simple implementation. I had to write 3 functions to implement this.

  • handleChange – triggers when a user types anything on the text box
  • isPrime – this method checks whether the given number is a prime or not
  • handleClick – triggers when the user clicks on Check button and responsible for generating the result text.

Since React is coupled with states the component will be automatically rendered when the state changes. So there is no necessary to update the view separately. In addition to that, React tries to align with pure Javascript in order to provide more flexibility. But still, there is some learning curve.

Angular

Let’s check the implementation of Angular. If you are interested in Demo, please find it here.

app.component.ts

@Component({
  selector: "app-root",
  templateUrl: "./app.component.html",
  styleUrls: ["./app.component.css"]
})
export class AppComponent {
  value: any;
  result: String;
  classValue: String;
  text: String;

  isPrime (num: number){
    for(let i = 2; i < num; i++)
      if(num % i === 0) return false;
    return num > 1;
  }

  updateDisplayText() {
    if (this.result === "YES") {
      this.text = `${this.value} is a prime number`;
      this.classValue = "success panel";
    } else if (this.result === "NO") {
      this.text = `${this.value} is not a prime number`;
      this.classValue="error panel";
    } else if (this.result === "ERROR") {
      this.text = `${this.value} is not a number`;
      this.classValue="error panel";
    }
  }

  checkPrime() {
    if (isNaN(this.value)) {
      this.result = "ERROR";
    } else {
        const isPrime = num => {
          for(let i = 2; i < num; i++)
            if(num % i === 0) return false;
          return num > 1;
        }

      this.result = isPrime(parseInt(this.value, 10)) ? "YES": "NO";

      this.updateDisplayText();
    }
  }

}

app-component.html

<div class="app">
  <div>
    <p>Enter number to verify prime number</p>
    <input type="text" class="input" [(ngModel)]="value"/>
  </div>
  <div>
    <button class="button" (click)="checkPrime()">Check</button>
  </div>
  <div [ngClass]="classValue">{{text}}</div>
</div>

Angular provides separation between view and logic. This improves the way of understanding. But in the context of angular, there are lots of stuff coming from the framework. So the learning curve will be higher when comparing with others. Since there are no states to bind with UI here, updateDisplayText function needs to be called at the end of the checkPrime function to update the display value. Because of this, the responsibility of the function changed into updating the view. Interpolation in template syntax will be used to provide dynamic behaviour.

VueJS

Let’s check the implementation of VueJS. If you are interested in Demo, please find it here.

<template>
  <div class="app">
      <div>
        <p>Enter number to verify prime number</p>
        <input type="text" class="input" v-model="value"/>
      </div>
      <div>
        <button class="button" :click="checkPrime">Check</button>
      </div>
      <div :class="classValue">{{text}}</div>
  </div>
</template>

<script>
export default {
  data: function() {
    return {
      value: "",
      result: "",
      classValue: "",
      isPrime: "",
      text: "",
    }
  },
  watch: {
    result: function () {
      if (this.result === "YES") {
        this.text = `${this.value} is a prime number`;
        this.classValue = "success panel";
      } else if (this.result === "NO") {
        this.text = `${this.value} is not a prime number`;
        this.classValue="error panel";
      } else if (this.result === "ERROR") {
        this.text = `${this.value} is not a number`;
        this.classValue="error panel";
      }
    },

  },
  methods: {
    checkPrime: function () {
      if (isNaN(this.value)) {
        this.result = "ERROR";
      } else {
          const isPrime = num => {
            for(let i = 2; i < num; i++)
              if(num % i === 0) return false;
            return num > 1;
          }

        this.result = isPrime(parseInt(this.value, 10)) ? "YES": "NO";
      }
    }
  }
};
</script>

<!-- Add "scoped" attribute to limit CSS to this component only -->
<style scoped>
	/* CSS will be here */
</style>

Vue is much like a combination of React and Angular in the code structure perspective. Vue provides a way to join view and logic inside the component. It is also a framework like Angular and still needs some background knowledge about the framework to start writing.

VueJS provides watchers. There are times when a custom watcher is necessary. Vue provides a more generic way to react to data changes through the watch option. This is most useful when you want to perform asynchronous or expensive operations in response to changing data. Because of this feature View and Logic separation in VueJS is higher than Angular.

Here I have provided a general idea of how I felt about these technologies while implementing this same functionality. There may be several ways of doing this or better ways. I just used the basic methods to approach this.

Thanks for reading. Did this article help you out? If it did, I hope you consider sharing it. You might help someone else out. Thanks so much!

Share with your friends!

2 Replies to “I tried writing a prime number checker using React, Angular and VueJS”

  1. Hi there just wanted to give you a quick heads up. The words in your content seem to be
    running off the screen in Firefox. I’m not sure if this is a
    formatting issue or something to do with internet browser
    compatibility but I thought I’d post to let you know.

    The layout look great though! Hope you get the problem solved soon.
    Many thanks

Leave a Reply

Your email address will not be published. Required fields are marked *