July 9

Calculator with React Pt. 1: Buttons!

So these last past days I’ve been watching a lot of React videos from Codevolution, and I also completed the React + Redux course in the SoloLearn app!

Yet another certificate for my collection!

In my opinion, the best way to learn is to be practical with what you are trying to learn. So I figured I would try to build a simple calculator app with React using what I’ve learned so far!

So in React we use something called “Components”. They are the building blocks of a React app. Components kinda work like functions or a classes in JavaScript, but they can accept input through something called “props”, and they each have their own “state”. Components returns HTML content through a render function. Usually we wanna split code into as many components as possible. That way our code is easier to read and also reusable.

Now our main file to work in is gonna be “src/App.js”. In “App.js” there’s some demo content which comes with React, but we can just remove that. Now we are left with:


import React, { createElement } from 'react';
import './App.css';

export default class App extends React.Component {

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

First thing we are gonna is to make a Button component! We can choose between a functional component or a class component. Since I haven’t learned about hooks yet, I’m gonna choose class component since I need to be able to set the state. For our props we want to take in what type the button should be, be able to determine if the button should be regular sized or wide, and if it needs a special color. Our constructor ends up looking like this:


    constructor(props) {
        super(props);

        this.buttonValue = props.buttonValue;

        //Set Button styling
        let p = props;

        if (p.wide && p.color === "red") {
            this.className = "component-button wide red";
        } else if (p.wide) {
            this.className = "component-button wide";
        } else if (p.color === "blue") {
            this.className = "component-button blue";
        } else {
            this.className = "component-button";
        }

    }

The props are being automatically sent by React, so all we need to do is to make a constructor which takes props and send them in the super function. We can use some if statements with the props and a variable, “className”, to change which CSS class the button should use for rendering.

Now, for our render function. The render function will be automatically called by React when the component is first created or when it notices that the components props or state has changed. This is actually one of the main features that makes React awesome and very performance effective! Instead of having to refresh the entire DOM (Document Object Model), React creates a Virtual DOM and re-renders only the necessary parts!

Now let me show my buttons render function:


    render() {
        return (
            <div>
                <button className={this.className} onClick={() => this.props.clickHandler(this.buttonValue)}>{this.buttonValue}</button>
            </div>
        )
    }

As we can see it looks like we are returning some HTML content, but there’s also some curly braces with JavaScript in them? This is actually the JSX syntax. With JSX we can write both HTML and JavaScript together! To use variables we just have to write a them inside curly braces. What’s happening in the background is that the JSX code is being transpiled into JavaScript. The code is being transformed into JavaScript using Reacts createElement function. So this means that you can just use the createElement function instead of JSX, but I reeeeeally don’t recommend that. Also note that React uses “className” instead of “class”!

For our clickHandler we are actually using a function that we are gonna create in the “App.js” file. The reason for this is that it’s the easiest way to communicate between a “child” component (the button) and a “parent” component (the “App”). Since we are using JavaScript we can just pass down the function to the child using props, and then set it in the render function! Pretty cool!

I’ve set up some CSS files for our App component and our Button component. I’m not gonna in depth about them, but just know to use CSS with React you have to import the files.

App.css

body {
  background-color: #d6d6d6;
}
[collapse]
Button.css

.component-button {
    width: 25%;
    height: 50px;
    font-family: "Calibri";
    font-size: 1.75rem;
    float:left;
    outline:none;
    
}   

.component-button.wide {
    width: 50%;
}

/* Red button */
.component-button.red {
    background-color: #ff5d5d;
}

.component-button.red:hover {
    background-color: #ff4949;
}

.component-button.red:active {
    background-color: #ff5d5d;
}

/* Blue button */
.component-button.blue {
    background-color: #5d93ff;
}

.component-button.blue:hover {
    background-color: #4a85fc;
}

.component-button.blue:active {
    background-color: #5d93ff;
}
[collapse]

Now, let’s see the buttons! In our “App.js” we import the Button component and then create them in our render function:


import React, { createElement } from 'react';
import './App.css';
import Button from './components/Button';

export default class App extends React.Component {

  clickHandler = buttonValue => {
    //ClickHandler for Button
  }

  render() {
    return (
      <div className="App">
        {/* Row 5 */}
        <Button buttonValue="CE" wide color="red" />
        <Button buttonValue="←" wide />

        {/* Row 4 */}
        <Button buttonValue="7" clickHandler={this.clickHandler} />
        <Button buttonValue="8" clickHandler={this.clickHandler} />
        <Button buttonValue="9" clickHandler={this.clickHandler} />
        <Button buttonValue="x" />

        {/* Row 3 */}
        <Button buttonValue="4" clickHandler={this.clickHandler} />
        <Button buttonValue="5" clickHandler={this.clickHandler} />
        <Button buttonValue="6" clickHandler={this.clickHandler} />
        <Button buttonValue="-" />

        {/* Row 2 */}
        <Button buttonValue="1" clickHandler={this.clickHandler} />
        <Button buttonValue="2" clickHandler={this.clickHandler} />
        <Button buttonValue="3" clickHandler={this.clickHandler} />
        <Button buttonValue="+" />

        {/* Row 1 */}
        <Button buttonValue="0" wide clickHandler={this.clickHandler} />
        <Button buttonValue="," />
        <Button buttonValue="=" color="blue" />
      </div>
    );
  }
}

And now we have a nice calculator layout with some buttons to press!

Animated GIF

And that’s it for this time! I noticed afterwards that the division operator is missing, but I’ll fix that next time!



Copyright 2020. All rights reserved.

Posted July 9, 2020 by Atle in category "ReactJS

Leave a Reply

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