React.js Basic Arithmetic Calculator

| Page Views: 40

How to Create a Basic Arithmetic Calculator using React.js

This is a beginners introduction to React.js example. We want to see how to use React to create a simple hello world calculator. Our calculator will be able to perform basic arithmetics like Addition,substraction,division,multiplication and modulo.

This also provides us with an opportunity to taste various arithmetic operators in Javascript.

React Basic Calculator

Video Tutorial

You can view the video tutorial below. It has more explanations on what we are doing.

(a). style.css
body {
  display: flex;
  justify-content: center;
  background: #009968;
}

input{
  padding: 10px;
  color: black;
  border-style: solid;
  font-weight: bold;
  border-color: coral;
  width: 100px;
  line-height: 1.5rem;
}
button {
  line-height: 1.5rem;
  font-size: 2rem;
  font-weight: bold;
  padding: 10px;
  width: 50px;
  color: white;
  background: coral;
}
/* end */
(b). index.js

This is where we write our main react code.

// We start by importing modules using import statement.
//Let's import `React` namespace from `react` module.
import React from 'react';
// Then render from `react-dom` module.
import { render } from 'react-dom';
//Then our styles.css
import './style.css';

// Let's create a component called `App` inheriting from React.Component
class App extends React.Component {
    // Let's create a property of our component called state that will mainatain
    //two numbers.
    state = {
        firstOperand: 0,
        secondOperand: 0
    };

    updateInputValue = (evt) => {
    const { name, value } = evt.target;
    //Let's use the `setState()` to  update the user interface in response to
    // event handlers and server responses.
        this.setState({
      // Convert string to integer
            [name]: parseInt(value)
        });
    };

  //Let's create a method to perform addition and show result.
    add = () => {
        const { firstOperand, secondOperand } = this.state;
        alert('Addition Result: ' + (firstOperand + secondOperand));
    };

  // Let's create a method to perform substraction and show result.
    substract = () => {
        const { firstOperand, secondOperand } = this.state;
        alert('Subtraction Result:  ' + (firstOperand - secondOperand));
    };

  // Let's create a method to perform division and show result.
    divide = () => {
        const { firstOperand, secondOperand } = this.state;
        alert('Division Result: ' + firstOperand / secondOperand);
    };

  // Let's create a method to perform multiplication and show result.
    multiply = () => {
        const { firstOperand, secondOperand } = this.state;
        alert('Multiplication Result: ' + firstOperand * secondOperand);
    };

  // Let's create a method to perform modulus and show result.
    modulus = () => {
        const { firstOperand, secondOperand } = this.state;
        alert('Modulus Result: ' + firstOperand % secondOperand);
    };

  // Let's come rebder our ui elements using JSX
    render() {
        return (
            <div>
                <div>
                    <input
                        placeholder=""
                        value={this.state.inputValue}
                        name="firstOperand"
                        onChange={(evt) => this.updateInputValue(evt)}
                    />
                    <input
                        placeholder=""
                        value={this.state.inputValue}
                        name="secondOperand"
                        onChange={(evt) => this.updateInputValue(evt)}
                    />
                </div>
                <div>
                    <button onClick={this.add}>+</button>
                    <button onClick={this.substract}>-</button>
                    <button onClick={this.divide}> / </button>
                    <button onClick={this.multiply}> * </button>
                    <button onClick={this.modulus}> % </button>
                </div>
            </div>
        );
    }
}
// Let's now come render our App component
render(<App />, document.getElementById('root'));
(c)index.html

This is our main html public file.

<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no">
    <meta name="theme-color" content="#009968">

    <link rel="manifest" href="%PUBLIC_URL%/manifest.json">
    <link rel="shortcut icon" href="%PUBLIC_URL%/favicon.ico">
    <title>Tasting React</title>
</head>

<body>
    <noscript>
        You need to enable JavaScript to run this app.
    </noscript>
    <div id="root"></div>
</body>

</html>
Download

You can download the full source code below or watch the video from the link provided.

No. Location Link
1. GitHub Direct Download
2. GitHub Browse
3. YouTube Video Tutorial
4. YouTube ProgrammingWizards TV Channel

How do You Feel after reading this?

According to scientists, we humans have 8 primary innate emotions: joy, acceptance, fear, surprise, sadness, disgust, anger, and anticipation. Feel free to tell us how you feel about this article using these emotes or via the comment section.

About Me.

After completing his Software Engineering bachelors program, Oclemy(Clement Ochieng) these days is a man of two lives. At day he works for a startup in Nairobi, Kenya. At night he works tirelessly on building ProgrammingWizards TV, a tv channel for student coders and this website to help share the source code. In between he practices Meditation and Self actualization to help him keep balance. He also likes going for long solo walks to connect more with nature.




Recommendations


What do You Think


Previous Post Next Post