We create a calculator-converter based on React. Part 4: Decomposition and minor corrections

We continue to develop a calculator-converter based on Reakt with the Chakra visual library. This article discusses decomposition, as well as eliminating minor flaws in the code and changing some aspects of the design. We will lightly comb our program, as well as prepare it to add new features and implement the converter in future materials.

Previous material: React-based calculator converter. Part 3: Automatic calculation of results

Why do you need decomposition?

The division of the program into parts is motivated by the need to have complete control over every aspect of the program, so that you can easily find the right piece of code and, if desired, make changes to it. Also, dividing the program into parts allows you to make individual components of the interface or logic independent of each other. This, in turn, makes the final product more resistant to failure. Even if one part of the software fails, it will not affect the others (if set up correctly, of course).

We’ll start splitting a single block of code into separate files to make it easier to add new components to the interface.

The community is now in the Telegram

Subscribe and stay up to date with the latest IT news

Sign up

Break the application into parts

Take a look at our primitive calculator. It is only capable of performing basic calculations, but has already stretched over a significant amount of code. It turns out quite a large canvas, which is difficult to follow. Here it is difficult to find the necessary components and edit them. If all the components of the calculator were placed in separate files, some of the problems with code readability would simply disappear.

Calculator code in one file

Let’s start by creating a separate directory in the src folder where our jsx files are located. Let’s call it components and create three separate components: Calculator, ClickCalc and InputCalc.

React components

As for the last two, they will almost not have to change, but the first will have to be significantly adjusted, because it will be a completely new element. A similar fate awaits the App.jsx component, which will almost lose the code at the moment.

The screenshot below shows what the InputCalc component might look like in a separate file. You will not be able to see any special differences here. This is the same React function, with the same logic and a similar interface returned from the return method.

The contents of the InputCalc component

From the new here only export. For this component to be available inside other items, you need to export it:


export default InputCalc

A similar procedure should be performed for all components selected in separate files so that you can import them to other parts of the calculator at once. It is important to note that you only need to export the root object, and you do not need to export functions that are connected within a single file. For example, you should not export Numbers and CountButton from a ClickCalc file. The ClickCalc function will notify other components of the existence of these objects anyway.

Export function to JavaScript

The next step is to create a generic component to select the calculator mode. Let me remind you that in the last article we made a smart string that automatically considers the values ​​of expressions entered into a special input element. But it exists next to the usual calculator, which does not suit us. In my opinion, these modes should be independent and located in different parts of the interface. It should also be possible to change one-click click modes. We will now implement such functionality.

The Calculator file will contain the following code:

React-component Calculator

  • First we import all the necessary components from the Chakra library.


    
    import { Box, Text, Button, Input, Flex } from '@chakra-ui/react'

  • Import the useState function:


    
    import { useState } from 'react'

  • Import the ClickCalc file (you can immediately capture another mode):


    
    import ClickCalc from '.ClickCalc'

  • Create a Calculator function:


    
    function Calculator () { }

  • In the body of the function we prescribe its state. In our case calcType. It will display the calculator mode used at a particular time. We leave ClickCalc by default so that the first thing the user saw when opening our program was the standard calculator interface.


    
    const [calcType, setCalcType] = useState('ClickCalc')

  • We also create a calculator variable that will store the component with the desired mode.

  • We return this variable from the Calculator function:


    
    return ( <Box> {calculator} </Box> )

Now you need to add a switch construct that changes the value of the calculator variable depending on what kind of calculator you want to see in front of you.

Switch design in Calculator component

  • Prescribe the design itself with the desired value:


    
    switch (calcType) { }

  • In the body of the switch we prescribe two cases. The first for a situation where a standard calculator should work:


    
    case 'ClickCalc': calculator = <ClickCalc />; break;

  • And the second for the smart field to count using the eval function:


    
    case 'InputCalc': calculator = <InputCalc />; break;

  • And the default case:


    
    default: calculator = <ClickCalc />

Now we need a button that is responsible for switching between the two modes of the program. Add the Button to the interface by turning the calculator variable and the button into a single Box.

Component calculator interface

The buttons must have a toggle function. It looks like this:


onClick={() => { calcType == 'ClickCalc' ? setCalcType('InputCalc') : setCalcType('ClickCalc') }}

This function checks the value of the calcType status and changes it to another depending on what is specified at the time of the click (using the ternary operator ?).

Function for switching between calculators

This feature can be transferred to the body of the component, and in the interface leave only access to it on click, as described below.

Calculator layout

All we have to do is import Calculator into the App file.

Import the Calculator component to the root of the program

As you can see, we previously deleted almost all the code from the App file. There are only two imports left and the return of the component we need. That’s enough for now. Our switch and two different calculators are ready.

Adjust the resolution and position of objects

Now let’s move on to all the little things. For example, let’s adjust the interface. Now it is quite small and slips forever, because the incorrect values ​​of height and width are specified.

I recommend setting a fixed value of 90% width for the object, which displays the current value of the string for calculations. So it will stop sticking to the walls.

ClickCalc layout

Remove the fixed height value from all elements (except the main one, as specified in App.jsx), so that they do not affect the position of the program in the interface.

Resize buttons, make them bigger. I chose a width and length of 60 pixels.

Resized buttons

In this case, the elements look quite large on a mobile device.

Calculator interface on mobile device

We change the theme of design

We can also expand the capabilities of the theme used. I don’t like to specify colors in hex code with hex values, so I created an object theme inside the App and prescribed clearer names for the colors used (you can choose names to your liking).

An object with an advanced theme for Chakra UI

  • We import a function to App.jsx to expand the list of properties of the standard Chakra theme.


    
    import { extendTheme } from '@chakra-ui/react'

  • Create a variable with the extendTheme function and specify the changed properties of the theme:


    
    const theme = extendTheme({ colors: { capri: '#00C0F9, tomato: '#FF6347, }, })'

  • Then add the theme attribute to ChakraProvider:


    
    <ChakraProvider theme={theme}> </ChakraProvider>

Other small changes

We will add a few more small changes, for which it is a pity to start a new material.

We will add to the list of possibilities of the button “Exactly” complete reset of a search bar that it was not necessary to wash the entered values. By the way, you should add a separate button in case you want to delete all the characters entered.

Expression alignment button

Let’s change the array with numbers. Let’s write down all the numbers by hand to follow the order that has been used in calculators for centuries and is familiar to everyone who has come across them. In addition, we can add to the list of buttons and others.


const nums = ['7', '8', '9', '4', '5', '6', '1', '2', '3', '0', ',']... 

The component that is responsible for rendering numbers

After that, our calculator will have the usual look (except for a slightly curved layout).

Updated calculator interface with new number order

You can simplify your work with the smart calculator by adding autofocus to the input field. You don’t have to reach for it and click the mouse.

To do this, use the useEffect function, which we first import into the InputCalc component:


import { useState, useEffect } from 'react'

Import React-hook useEffect

Then we will declare this function inside InputCalc, and its bodies we will register the JavaScript method for focusing on the input element.


useEffect(() => { document.querySelector("input").focus() })

Focus on the element with useEffect

Instead of imprisonment

That’s all. We’ve broken down the application and fixed a number of issues. Now let’s move on to the implementation of new features. If you have any questions or tips, be sure to leave them in the comments.

Related Posts

Leave a Reply

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

© 2023 ZoNa365.ru - Theme by WPEnjoy · Powered by WordPress