This Tutorial POST ReactJS part 2, If you missed part 1 please read it here. In this tutorial, we focus on creating the front-end and implementing ReactJS Programming. If you are a beginner’s ReactJS, please read the ReactJS basic tutorial first. This is important to know, you won’t be able to successfully follow this tutorial if you don’t understand some prior knowledge about ReactJS. The difference between using Javascript is the way of thinking and the Work with React Concept. You can read more about React understanding at React official site.
What features are presented in this simple POS application?
- Create CRUD and item lists.
- Create CRUD and customer lists.
- Create a simple POS UX that integrates with goods and customers.
The final result of this tutorial, we build an application like the following image
This POS application is quite simple, the main purpose of this tutorial is How to implement ReactJS for the front-end development of business applications. Ok, let’s get started.
Table of Contents
Create a simple POS application using ReactJS
List of supporting libraries used (Here is the version I used when this application was created)
- react version 17.0.1
- react-datepicker version ^3.4.1
- react-number-format version ^4.4.4
- react-router-dom version ^5.2.0
- react-select version ^3.2.0
- react-toastify version ^6.2.0
- reactstrap version ^8.7.1
- @fortawesome/fontawesome-svg-core version ^1.2.32
- @fortawesome/free-brands-svg-icons version ^5.15.1
- @fortawesome/free-regular-svg-icons version ^5.15.1
- @fortawesome/free-solid-svg-icons version ^5.15.1
- @fortawesome/react-fontawesome version ^0.1.13
- @testing-library/jest-dom version ^5.11.6
- @testing-library/react version ^11.2.2
- @testing-library/user-event version ^12.6.0
- axios version ^0.21.0
- bootstrap version ^4.5.3
Create ReactJS new project
1 | npx create-react-app sample-post-reactjs |
Supporting library installation
To speed up the supporting libraries installation, please copy the following package list and add it in the dependency key in the package.json file in the top folder of your project.
1 2 3 4 5 6 7 8 9 10 11 12 13 | "@fortawesome/fontawesome-svg-core": "^1.2.32", "@fortawesome/free-brands-svg-icons": "^5.15.1", "@fortawesome/free-regular-svg-icons": "^5.15.1", "@fortawesome/free-solid-svg-icons": "^5.15.1", "@fortawesome/react-fontawesome": "^0.1.13", "axios": "^0.21.0", "bootstrap": "^4.5.3", "react-datepicker": "^3.4.1", "react-number-format": "^4.4.4", "react-router-dom": "^5.2.0", "react-select": "^3.2.0", "react-toastify": "^6.2.0", "reactstrap": "^8.7.1" |
After copying and then running the script “npm install” in the project folder (Let npm do the installation of all dependencies so the application working normally).
At this point, you have finished the initial installation of ReactJS. The next step is to create 4 main folders inside the “sample-post-reactjs/src” folder.
POS Project Main Files
The four folders are :
- assets: the assets folder used to store all supporting media files such as images.
- components: the components folder used to store all additional components that are used to speed up the build. (One of the advantages of ReactJS – the reusable components)
- services: the services folder used to store the support’s modules such as a collection of API requests, default constants used globally.
- pages: the pages folder used to store all the main files of application pages to form a POS application. All application pages will be placed in this folder.
Okay, Here is the complete explanation :
assets
At this time, the assets folder only contains a folder called image and all supporting images can be download at my GitHub page.
components
All reusable components are stored in this folder. In this ReactJS simple point of sales example, we create a reusable component namely the custom modal dialog form. Here’s how to create a reusable modal dialog sidebar:
Create custom ReactJS sidebar dialog modal.
If you are tired of bootstrap’s standard dialog modal display, this Custom modal dialog can be an alternative. You can modify it by yourself according to the application needed. The sidebar dialog modal that is created will be like the following image:
How to create a modal dialog sidebar component in ReactJs
- Create a new folder named CustomModal in the components folder.
- Create 2 js and css files as index.js and index.css.
- Copy the following js code in the index.js file12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152import React, { useEffect, useCallback } from "react";import "./index.css";import { useHistory } from "react-router-dom";import { Button } from "reactstrap";function CustomModal({ title, children }) {let history = useHistory();const escFunction = useCallback((event) => {if (event.keyCode === 27) {history.goBack();}},[history]);useEffect(() => {document.addEventListener("keydown", escFunction, false);return () => {document.removeEventListener("keydown", escFunction, false);};}, [escFunction]);return (<div className="container-custom-modal" onClick={() => history.goBack()}><divclassName="container-inner-modal"onClick={(e) => e.stopPropagation()}><div className="container-inner-modal-header"><h2 className="page-header">{title}</h2><ButtoncloseonClick={() => history.goBack()}style={{color: "#000",fontSize: "29px",marginRight: "5px",}}/></div><div className="container-inner-modal-content">{children}</div></div></div>);}CustomModal.defaultProps = {title: "Title",};export default CustomModal;
- copy the following css code in the index.css file12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758.container-custom-modal {position: absolute;top: 110px;right: 0;bottom: 0;width: 100%;background-color: rgba(0, 0, 0, 0.7);z-index: 1024;height: 100%;}h2.page-header {font-size: 20px;margin-bottom: 0px;}.container-inner-modal {position: absolute;width: 100%;top: 0;right: 0;bottom: 0;background-color: rgb(255, 255, 255);}.container-inner-modal-header {padding: 5px 15px;background-color: #dfdfdf;}.container-inner-modal-header button {position: absolute;top: 5px;right: 5px;background-color: Transparent;background-repeat: no-repeat;border: none;cursor: pointer;overflow: hidden;outline: none;}.container-inner-modal-content {padding: 15px;}@media (min-width: 576px) {.container-inner-modal {width: 75%;}.container-custom-modal {top: 60px;}}@media (min-width: 768px) {}@media (min-width: 992px) {}@media (min-width: 1200px) {}
How to use the ReactJS sidebar modal dialog can be seen when we create the item master form and customer master form.
services
The service folder is used to store the files that contain variables that frequently use or can be referred to as a global variable.
There are 2 files in the services folder, namely the request folder and the constants.js file
Request folder is a folder that is used to store all Axios settings and Axios commands for creating the requests to the API server. All actions related to request data to the API server will be stored in the folder, so the file is tidier and easier to maintain
Some of the files contained in the request folder:
– AxiosDefault.js
Copy the following code into the AxiosDefault.js file
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 | import axios from "axios"; import { path_server, request_delay } from "../Constants"; const api_token = localStorage.getItem("token") ? localStorage.getItem("token") : ""; export const api = axios.create({ baseURL: path_server, timeout: request_delay, headers: { token: api_token, }, }); export const noAuthAPI = axios.create({ baseURL: path_server, timeout: request_delay, }); |
A brief description :
Here we create 2 new instances of the Axios class as default, namely the API constant and the noAuthApi constant.
The difference between the two instances is :
- API: used if the request to the API server requires a token key. The token will be placed in the request header when a data request is sent by the application to the API server.
- noAuthApi: an instance that is used to make requests to the API server without requiring a token key. like a login request.
– Customer.js
The Customer.js file is used to store all business rules related to customer data.
Copy the following code into Customer.js
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 | import { noAuthAPI } from "./AxiosDefault"; const customerAdd = (obj) => { return noAuthAPI.post("/customer/add", obj); }; const customerEdit = (obj) => { return noAuthAPI.post("/customer/edit", obj); }; const customerDelete = (obj) => { return noAuthAPI.post("/customer/delete", obj); }; const customerGet = (obj) => { return noAuthAPI.get("/customer/get", { params: obj }); }; const customerList = (obj) => { return noAuthAPI.get("/customer/list", { params: obj }); }; const customerSearch = (obj) => { return noAuthAPI.get("/customer/search", { params: obj }); }; const CustomerAPI = { customerAdd, customerEdit, customerDelete, customerGet, customerList, customerSearch, }; export default CustomerAPI; |
Explanation:
There are 2 types of requests made to customer.js, get and post. Surely you already know what get and post requests are. In Axios, the way to use parameters in GET and POST requests is different.
- get: the parameter type is an object and placed it in the other object ({params: obj})1axios.get("/customer/list", { params: obj });
- post: the parameter type is an object and is immediately installed without any additional objects.1axios.post("/customer/delete", obj);
- customerAdd is used to create new customers.
- customerEdit is used to edit customers.
- customerDelete is used to delete customers.
- customerGet is used to retrieve customer data based on id.
- customerList is used to retrieve customer lists.
- customerSearch is used to search for customers by name
– Item.js
The Item.js used to store all business rules related to item data.
Copy the following code into Item.js
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 | import { noAuthAPI } from "./AxiosDefault"; const itemAdd = (obj) => { return noAuthAPI.post("/item/add", obj); }; const itemEdit = (obj) => { return noAuthAPI.post("/item/edit", obj); }; const itemDelete = (obj) => { return noAuthAPI.post("/item/delete", obj); }; const itemGet = (obj) => { return noAuthAPI.get("/item/get", { params: obj }); }; const itemList = (obj) => { return noAuthAPI.get("/item/list", { params: obj }); }; const itemSearch = (obj) => { return noAuthAPI.get("/item/search", { params: obj }); }; const ItemAPI = { itemAdd, itemEdit, itemDelete, itemGet, itemList, itemSearch, }; export default ItemAPI; |
Explanation
- itemAdd is used to create new items.
- itemEdit is used to edit items.
- itemDelete is used to delete.
- itemGet is used to retrieve item data by id.
- itemList is used to retrieve a list of items.
- itemSearch is used to search for items by name
– Sales.js
Sales.js used to store all business rules related to sales data. Copy the following code into Sales.js
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 | import { noAuthAPI } from "./AxiosDefault"; const salesAdd = (obj) => { return noAuthAPI.post("/sales/add", obj); }; const salesDelete = (obj) => { return noAuthAPI.post("/sales/delete", obj); }; const salesGet = (obj) => { return noAuthAPI.get("/sales/get", { params: obj }); }; const salesList = (obj) => { return noAuthAPI.get("/sales/list", { params: obj }); }; const SalesAPI = { salesAdd, salesDelete, salesGet, salesList, }; export default SalesAPI; |
Explanation
- salesAdd is used to create new sales.
- salesDelete is used to delete sales.
- salesGet is used to retrieve sales data based on sales id.
- salesList is used to retrieve sales lists
– ErrorReq.js
This file used to manage all error responses obtained when a request to the server fails and displays error messages as notification toasts.
Copy the following code into ErrorReq.js
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 | import { toast } from "react-toastify"; import { request_delay } from "../Constants"; const ToastError = (err) => { if ( !("response" in err) || err.message === "Network Error" || err.message === "timeout of " + request_delay.toString() + "ms exceeded" ) { toast.error(err.message); } else { let error = err.response; if ( error.status === "401" || error.status === "400" || error.status === "500" || error.status === "498" ) { let msg = error.data.message; toast.error("Error " + error.status + " - " + msg); } if (error.status === "404") { toast.error("Error " + error.status + " - API Not Found"); } if (error.status === "405") { toast.error("Error " + error.status + " - Method Not Allowed"); } } }; export default ToastError; |
– index.js
The index.js used as the main file to export all files in the request folder
Copy the following code to index.js
1 2 3 4 | export * from "./Item"; export * from "./Customer"; export * from "./toastError"; export * from "./Sales"; |
– Constants.js
At this time, the Constants.js file consists of only 2 lines of code. This file is for storing the path_server and request_delay constants
- path_server used to save API Server URL.
- request_delay to store the length of timeout used by Axios when making a request.
Copy the following code to Constansts.js
1 2 | export const path_server = "http://localhost:8000"; export const request_delay = 300000; |
If the four folders above and their contents have been created, the next step is to create the main file of the ReactJS POS application, namely the pages folder.
pages
The pages folder contains the main components that are used to assemble several components into a single point of sales application. The four components are the customer component, item, sales list, and POS component.
Create 4 folders inside the pages folder, namely
customer
customer components are used to create the customer interfaces. This component runs the process of creating new customers, editing, retrieving customer data, viewing customer lists, and deleting customers.
Create index.js in the customer folder
copy the following code
index.js
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 | import React from "react"; import CustomModal from "../../components/CustomModal"; import { Table, ButtonGroup, Button, Modal, ModalHeader, FormFeedback, Label, FormGroup, Input, Col, Form, ModalBody, ModalFooter, } from "reactstrap"; import CustomerAPI from "../../services/request/Customer"; import ToastError from "../../services/request/ErrorReq"; import { toast } from "react-toastify"; import { FontAwesomeIcon } from "@fortawesome/react-fontawesome"; import { faEdit, faPlus, faTrash } from "@fortawesome/free-solid-svg-icons"; const customer_validation_default = { customer_name_invalid: false, }; const customer_default = { customer_id: 0, customer_name: "", customer_address: "", customer_phone: "", }; class Customer extends React.Component { constructor(props) { super(props); this.state = { modalDialog: false, selected_customer: {}, list_customer: [], customer: customer_default, customer_validation: customer_validation_default, is_new: true, in_proses: false, }; } saveCustomer = () => { let req = this.state.customer; if (req.customer_name === "") { this.setState({ customer_validation: { ...this.state.customer_validation, customer_name_invalid: true, }, }); this.customerRef.focus(); return; } this.state.is_new ? this.saveNewcustomer() : this.editcustomer(); }; setCustomerToCart = (index) => { this.props.callbackRequest( this.state.list_customer[index].customer_id, this.state.list_customer[index].customer_name ); }; deleteCustomer = (id) => { CustomerAPI.customerDelete({ customer_id: id }) .then((result) => { toast.success(result.data.message); this.refreshCustomer(); }) .catch((err) => { ToastError(err); }); }; getCustomer = (index) => { this.setState({ customer: this.state.list_customer[index], is_new: false }); this.toggleModal(); }; saveNewcustomer() { CustomerAPI.customerAdd(this.state.customer) .then((result) => { toast.success(result.data.message); this.setState({ customer: customer_default }); this.customerRef.focus(); this.refreshCustomer(); }) .catch((err) => { ToastError(err); }); } editcustomer() { CustomerAPI.customerEdit(this.state.customer) .then((result) => { toast.success(result.data.message); this.refreshCustomer(); }) .catch((err) => { ToastError(err); }); } componentDidMount() { this.refreshCustomer(); } toggleModal = () => { this.setState({ modalDialog: !this.state.modalDialog }); }; refreshCustomer() { CustomerAPI.customerList() .then((result) => { this.setState({ list_customer: result.data.data, }); }) .catch((err) => { ToastError(err); }); } render() { const customerList = this.state.list_customer; return ( <CustomModal title="Customer"> <Button color="primary" onClick={this.toggleModal} className="mb-2"> + Add Customer </Button> <Table responsive hover borderless> <thead className="table-active"> <tr> <th>#</th> <th>Name</th> <th>Address</th> <th>Phone</th> <th></th> </tr> </thead> <tbody> {customerList.map((obj, index) => { return ( <tr key={index.toString()}> <td>{index + 1}</td> <td>{obj.customer_name}</td> <td>{obj.customer_address}</td> <td>{obj.customer_phone}</td> <td className="text-center"> <ButtonGroup size="sm"> <Button title="Add to cart" color="success" onClick={() => { this.setCustomerToCart(index); }} > <FontAwesomeIcon icon={faPlus} /> Add To Cart </Button> <Button title="Edit Customer" color="warning" onClick={() => { this.getCustomer(index); }} > <FontAwesomeIcon icon={faEdit} /> Edit </Button> <Button title="Delete Customer" onClick={() => { this.deleteCustomer(obj.customer_id); }} color="danger" > <FontAwesomeIcon icon={faTrash} /> Delete </Button> </ButtonGroup> </td> </tr> ); })} </tbody> </Table> <Modal isOpen={this.state.modalDialog} size="lg" toggle={this.toggleModal} > <ModalHeader toggle={this.toggleModal}> {this.state.is_new ? "New Customer" : "Edit Customer"} </ModalHeader> <ModalBody> <Form> <FormGroup row> <Label sm={3}>Customer Name</Label> <Col sm={8}> <Input invalid={ this.state.customer_validation.customer_name_invalid } autoFocus innerRef={(ref) => { this.customerRef = ref; }} size="sm" type="text" name="customer_name" value={this.state.customer.customer_name} placeholder="customer name" onChange={(event) => { const { target } = event; this.setState({ customer: { ...this.state.customer, customer_name: target.value, }, }); }} /> <FormFeedback tooltip>customer name is required</FormFeedback> </Col> </FormGroup> <FormGroup row> <Label sm={3}>Customer Address</Label> <Col sm={9}> <Input invalid={ this.state.customer_validation.customer_address_invalid } size="sm" type="textarea" value={this.state.customer.customer_address} placeholder="Customer address" onChange={(event) => { const { target } = event; this.setState({ customer: { ...this.state.customer, customer_address: target.value, }, }); }} /> </Col> </FormGroup> <FormGroup row> <Label sm={3}>Customer Phone</Label> <Col sm={4}> <Input invalid={ this.state.customer_validation.customer_phone_invalid } size="sm" type="text" value={this.state.customer.customer_phone} placeholder="Customer phone" onChange={(event) => { const { target } = event; this.setState({ customer: { ...this.state.customer, customer_phone: target.value, }, }); }} /> </Col> </FormGroup> </Form> </ModalBody> <ModalFooter> <Button color="secondary" onClick={this.toggleModal}> Cancel </Button>{" "} <Button color="primary" onClick={this.saveCustomer}> {this.state.is_new ? "Save New" : "Edit Customer"} </Button> </ModalFooter> </Modal> </CustomModal> ); } } export default Customer; |
item
The component item used to create new items and edit items
Create index.js in the items folder and copy the following code
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 | import React from "react"; import CustomModal from "../../components/CustomModal"; import { Col, Form, FormGroup, Label, Input, Button, FormFeedback, } from "reactstrap"; import NumberFormat from "react-number-format"; import ItemAPI from "../../services/request/Item"; import { toast } from "react-toastify"; import ToastError from "../../services/request/ErrorReq"; const item_validation_default = { item_name_invalid: false, item_package_invalid: false, }; const item_default = { item_id: 0, item_name: "", item_price: 0, item_stock: 0, item_package: "", }; class Item extends React.Component { constructor(props) { super(props); this.state = { item: props.new ? item_default : props.itemDetail, item_validation: item_validation_default, is_new: props.new, in_proses: false, }; } componentDidUpdate() {} componentDidMount() {} saveItem = () => { let req = this.state.item; if (req.item_name === "") { this.setState({ item_validation: { ...this.state.item_validation, item_name_invalid: true, }, }); this.itemRef.focus(); return; } if (req.item_package === "") { this.setState({ item_validation: { ...this.state.item_validation, item_package_invalid: true, }, }); this.packageRef.focus(); return; } this.state.is_new ? this.saveNewItem() : this.editItem(); }; saveNewItem() { ItemAPI.itemAdd(this.state.item) .then((result) => { toast.success(result.data.message); this.setState({ item: item_default }); this.itemRef.focus(); this.props.refreshItem(); }) .catch((err) => { ToastError(err); }); } editItem() { ItemAPI.itemEdit(this.state.item) .then((result) => { toast.success(result.data.message); this.itemRef.focus(); this.props.refreshItem(); }) .catch((err) => { ToastError(err); }); } render() { return ( <CustomModal title={this.state.is_new ? "New Item" : "Edit Item"}> <Form> <FormGroup row> <Label sm={2}>Item Name</Label> <Col sm={6}> <Input invalid={this.state.item_validation.item_name_invalid} autoFocus innerRef={(ref) => { this.itemRef = ref; }} size="sm" type="text" name="item_name" value={this.state.item.item_name} placeholder="Item name" onChange={(event) => { const { target } = event; this.setState({ item: { ...this.state.item, item_name: target.value, }, }); }} /> <FormFeedback tooltip>Item name is required</FormFeedback> </Col> </FormGroup> <FormGroup row> <Label sm={2}>Price</Label> <Col sm={6}> <NumberFormat className="form-control-sm form-control" placeholder="0" type="text" name="item_price" value={this.state.item.item_price} thousandSeparator={true} inputMode="numeric" onValueChange={(values) => { const { value } = values; this.setState({ item: { ...this.state.item, item_price: value, }, }); }} /> </Col> </FormGroup> <FormGroup row> <Label sm={2}>Stock</Label> <Col sm={6}> <NumberFormat className="form-control-sm form-control" placeholder="0" type="text" name="item_stock" value={this.state.item.item_stock} thousandSeparator={true} inputmode="numeric" onValueChange={(values) => { const { value } = values; this.setState({ item: { ...this.state.item, item_stock: value, }, }); }} /> </Col> </FormGroup> <FormGroup row> <Label sm={2}>Package</Label> <Col sm={6}> <Input invalid={this.state.item_validation.item_package_invalid} type="select" innerRef={(ref) => { this.packageRef = ref; }} defaultValue={this.state.item.item_package} onChange={(event) => { const { target } = event; this.setState({ item: { ...this.state.item, item_package: target.value, }, }); }} name="item_package" size="sm" > <option value="" disabled selected> Select package name </option> <option value="PCS">PCS</option> <option value="BOX">BOX</option> </Input> <FormFeedback tooltip>Package name is required</FormFeedback> </Col> </FormGroup> <FormGroup row> <Label sm={2}></Label> <Col sm={6}> <Button color="primary" onClick={this.saveItem} title="Save Item"> {this.props.new ? "Save Item" : "Edit Item"} </Button> </Col> </FormGroup> </Form> </CustomModal> ); } } export default Item; |
list
the list component used to display a sales list and delete sales transactions
Create index.js in the folder list and copy the following code.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 | import React from "react"; import "./index.css"; import CustomModal from "../../components/CustomModal"; import { Table, ButtonGroup, Button } from "reactstrap"; import SalesAPI from "../../services/request/Sales"; import ToastError from "../../services/request/ErrorReq"; import { toast } from "react-toastify"; import { FontAwesomeIcon } from "@fortawesome/react-fontawesome"; import { faTrash } from "@fortawesome/free-solid-svg-icons"; import NumberFormat from "react-number-format"; class List extends React.Component { constructor(props) { super(props); this.state = { list: [], }; } deleteSales = (id) => { SalesAPI.salesDelete({ sales_id: id }) .then((result) => { toast.success(result.data.message); this.refreshSales(); }) .catch((err) => { ToastError(err); }); }; componentDidMount() { this.refreshSales(); } refreshSales() { SalesAPI.salesList() .then((result) => { console.log(result); this.setState({ list: result.data.data, }); }) .catch((err) => { ToastError(err); }); } render() { const SalesList = this.state.list; return ( <CustomModal title="Sales"> <Table responsive hover borderless> <thead className="table-active"> <tr> <th>#</th> <th>Sales Date</th> <th>Customer</th> <th>Discount</th> <th>Total</th> <th></th> </tr> </thead> <tbody> {SalesList.map((obj, index) => { return ( <tr key={index.toString()}> <td>{index + 1}</td> <td>{obj.sales_date}</td> <td>{obj.customer_name}</td> <td> <NumberFormat value={obj.discount} displayType={"text"} thousandSeparator={true} /> </td> <td> <NumberFormat value={parseFloat(obj.total)} displayType={"text"} thousandSeparator={true} /> </td> <td className="text-center"> <ButtonGroup size="sm"> <Button title="Delete Sales" onClick={() => { this.deleteSales(obj.sales_id); }} color="danger" > <FontAwesomeIcon icon={faTrash} /> Delete </Button> </ButtonGroup> </td> </tr> ); })} </tbody> </Table> </CustomModal> ); } } export default List; |
POS Component
the pos component contains the point of sales main modules. In this component, we can create sales transactions, add to the shopping carts, add the customers to transactions, and store sales transactions.
The POS component is a parent component. Where this component will be called the several child components such as customer, item, and list.
Create 2 files index.js and index.css in the pos folder and copy the following code :
index.js
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 | import React from "react"; import { Row, Col, InputGroup, Input, InputGroupAddon, InputGroupText, Table, Button, ButtonGroup, ListGroup, ListGroupItem, } from "reactstrap"; import { Switch, Route } from "react-router-dom"; import { withRouter } from "react-router-dom"; import "./index.css"; import NumberFormat from "react-number-format"; import DatePicker from "react-datepicker"; import "react-datepicker/dist/react-datepicker.css"; import Customer from "../customer"; import Item from "../item"; import List from "../list"; import ItemAPI from "../../services/request/Item"; import SalesAPI from "../../services/request/Sales"; import ToastError from "../../services/request/ErrorReq"; import { toast } from "react-toastify"; import { FontAwesomeIcon } from "@fortawesome/react-fontawesome"; import { faCartPlus, faEdit, faSync, faTimes, faTrash, faUser, } from "@fortawesome/free-solid-svg-icons"; const CustomCalender = ({ value, onClick }) => ( <Button color="success" onClick={onClick}> {value} </Button> ); const format_mysql_date = (d) => { let month = "" + (d.getMonth() + 1); let day = "" + d.getDate(); let year = d.getFullYear(); if (month.length < 2) month = "0" + month; if (day.length < 2) day = "0" + day; return [year, month, day].join("-"); }; class POS extends React.Component { constructor(props) { super(props); this.state = { new_item: true, sales: { customer_id: 0, customer_name: "", sales_date_display: new Date(), sales_date: format_mysql_date(new Date()), discount: 0, list_cart: [], sub_total: 0, grand_total: 0, }, list_item: [], editItem: {}, search_item_keyword: "", refresh_animation: false, }; } cancelTransaction = () => { let y = window.confirm("Cancel Transaction ?"); y && this.resetObject(); }; refreshItem() { this.setState({ refresh_animation: true }); ItemAPI.itemList() .then((result) => { this.setState({ list_item: result.data.data, refresh_animation: false, }); }) .catch((err) => { ToastError(err); this.setState({ refresh_animation: false }); }); } newCustomer = () => { this.props.history.push("/customer"); }; listSales = () => { this.props.history.push("/list"); }; newItem = () => { this.setState({ new_item: true, editItem: {} }); this.props.history.push("/item"); }; editItem = (index) => { this.setState({ new_item: false, editItem: this.state.list_item[index] }); this.props.history.push("/item"); }; deleteItem = (index) => { let detail = this.state.list_item[index]; let del = window.confirm("Delete item : " + detail.item_name + " ?"); if (del) { ItemAPI.itemDelete({ item_id: detail.item_id }) .then((result) => { toast.success(result.data.message); this.refreshItem(); }) .catch((err) => { ToastError(err); }); } }; addCart = (index) => { let listCart = this.state.sales.list_cart; let newItem = this.state.list_item[index]; index = listCart.findIndex((x) => x.item_id === newItem.item_id); if (index < 0) { listCart.push({ item_name: newItem.item_name, item_qty: 1, item_price: parseFloat(newItem.item_price), item_id: newItem.item_id, item_subtotal: parseFloat(newItem.item_price), }); } else { listCart[index].item_qty += 1; listCart[index].item_subtotal = parseFloat(newItem.item_price) * parseFloat(listCart[index].item_qty); } this.setState({ sales: { ...this.state.sales, list_cart: listCart } }); }; handleDecQty = (index) => { let listCart = this.state.sales.list_cart; if (listCart[index].item_qty === 1) { return; } listCart[index].item_qty -= 1; listCart[index].item_subtotal = parseFloat(listCart[index].item_price) * parseFloat(listCart[index].item_qty); this.setState({ sales: { ...this.state.sales, list_cart: listCart } }); }; handleIncQty = (index) => { let listCart = this.state.sales.list_cart; listCart[index].item_qty += 1; listCart[index].item_subtotal = parseFloat(listCart[index].item_price) * parseFloat(listCart[index].item_qty); this.setState({ sales: { ...this.state.sales, list_cart: listCart } }); }; deleteCart = (index) => { let listCart = this.state.sales.list_cart; listCart.splice(index, 1); this.setState({ sales: { ...this.state.sales, list_cart: listCart } }); }; resetObject() { this.setState({ sales: { customer_id: 0, customer_name: "", sales_date_display: new Date(), sales_date: format_mysql_date(new Date()), discount: 0, list_cart: [], sub_total: 0, grand_total: 0, }, }); } payTransaction = (obj) => { let sales = this.state.sales; if (sales.customer_id === 0) { toast.error("Please choose customer before save"); this.newCustomer(); return; } if (sales.list_cart.length <= 0) { toast.error("Cart doesn't have any product"); return; } let y = window.confirm("Save payment transaction ?"); if (y) { SalesAPI.salesAdd(this.state.sales) .then((result) => { this.resetObject(); toast.success(result.data.message); }) .catch((err) => { ToastError(err); }); } }; setCustomer = (id, custname) => { this.setState({ sales: { ...this.state.sales, customer_id: id, customer_name: custname, }, }); this.props.history.goBack(); }; componentDidUpdate() {} componentDidMount() { this.refreshItem(); } render() { const itemlist = this.state.list_item; const searchword = this.state.search_item_keyword; const listCart = this.state.sales.list_cart; let disc = parseFloat(this.state.sales.discount); let subs = 0; this.state.sales.list_cart.forEach((obj) => { subs += parseFloat(obj.item_subtotal); }); let grand_total = subs - (subs * disc) / 100; let sub_total = subs; return ( <> <Row className="main-pos"> <Col sm={4}> <Col className="main-pos-left" sm={12}> <div className="container-header"> <div className="container-header-1"> <InputGroup> <DatePicker dateFormat="dd/MM/yyyy" selected={this.state.sales.sales_date_display} onChange={(date) => this.setState({ sales: { ...this.state.sales, sales_date_display: date, sales_date: format_mysql_date(date), }, }) } customInput={<CustomCalender />} /> <InputGroupAddon addonType="append"> <InputGroupText> <FontAwesomeIcon icon={faUser} /> </InputGroupText> </InputGroupAddon> </InputGroup> </div> <div className="container-header-2"> <Button color="info" onClick={this.newCustomer} block> {this.state.sales.customer_id === 0 ? "+ Add Customer" : this.state.sales.customer_name} </Button> </div> </div> <div className="container-cart"> <div className="container-cart-list"> <ListGroup flush> {listCart.map((obj, index) => { return ( <ListGroupItem key={index.toString()}> <div className="cart-name"> <div>{obj.item_name}</div> </div> <div className="cart-detail"> <div className="cart-1"> <Button onClick={() => { this.handleDecQty(index); }} size="sm" > - </Button> {" "} {obj.item_qty} {" "} <Button onClick={() => { this.handleIncQty(index); }} size="sm" > + </Button>{" "} x{" "} <NumberFormat value={obj.item_price} displayType={"text"} thousandSeparator={true} /> </div> <div className="cart-2"> <NumberFormat value={obj.item_subtotal} displayType={"text"} thousandSeparator={true} /> </div> <div className="cart-3"> <FontAwesomeIcon className="text-danger pointer-hand" title="Delete item from cart" icon={faTimes} onClick={() => { this.deleteCart(index); }} /> </div> </div> </ListGroupItem> ); })} </ListGroup> </div> <div className="container-cart-recap"> <div className="recap"> <div className="title">Total</div> <div className="result"> <NumberFormat value={sub_total} displayType={"text"} thousandSeparator={true} /> </div> </div> <div className="recap"> <div className="title">Discount</div> <div className="result"> <InputGroup size="sm"> <Input type="number" min="0" max="100" size="sm" onChange={(event) => { const { target } = event; this.setState({ sales: { ...this.state.sales, discount: target.value, }, }); }} value={this.state.sales.discount} placeholder="0" /> <InputGroupAddon addonType="append"> <InputGroupText>%</InputGroupText> </InputGroupAddon> </InputGroup> </div> </div> <div className="recap"> <div className="title">Net</div> <div className="result recap-net"> <NumberFormat value={grand_total} displayType={"text"} thousandSeparator={true} /> </div> </div> </div> </div> </Col> </Col> <Col sm={8}> <Col className="main-pos-right" sm={12}> <div className="mb-3"> <InputGroup size="sm"> <Input onChange={(event) => { const { target } = event; this.setState({ search_item_keyword: target.value }); }} placeholder="SEARCH PRODUCT HERE..." /> <InputGroupAddon addonType="append"> <ButtonGroup title="Refresh item list" size="sm"> <Button color="warning" onClick={() => { this.refreshItem(); }} > <FontAwesomeIcon spin={this.state.refresh_animation} icon={faSync} /> </Button> <Button color="primary" onClick={this.newItem}> {" "} + ADD NEW ITEM </Button> </ButtonGroup> </InputGroupAddon> </InputGroup> </div> <div> <Table responsive hover borderless> <thead className="table-active"> <tr> <th>#</th> <th>Item</th> <th className="text-right">Stock</th> <th className="text-right">Price</th> <th></th> </tr> </thead> <tbody> {itemlist .filter((itm) => itm.item_name .toUpperCase() .includes(searchword.toUpperCase()) ) .map((obj, index) => { return ( <tr key={index.toString()}> <td>{index + 1}</td> <td>{obj.item_name}</td> <td className="text-right">{obj.item_stock}</td> <td className="text-right">{obj.item_price}</td> <td className="text-center"> <ButtonGroup size="sm"> <Button onClick={() => { this.addCart(index); }} title="Add to cart" color="success" > <FontAwesomeIcon icon={faCartPlus} /> Add </Button> <Button title="Edit master item" color="warning" onClick={() => { this.editItem(index); }} > <FontAwesomeIcon icon={faEdit} /> Edit </Button> <Button title="Delete item" onClick={() => { this.deleteItem(index); }} color="danger" > <FontAwesomeIcon icon={faTrash} /> Delete </Button> </ButtonGroup> </td> </tr> ); })} </tbody> </Table> </div> <div> <Button onClick={this.payTransaction} color="success" className="mr-1" > PAYMENT </Button> <Button onClick={this.cancelTransaction} color="danger" className="mr-1" > CANCEL </Button> <Button onClick={this.listSales} color="info"> SALES'S LIST </Button> </div> </Col> </Col> </Row> <Switch> <Route exact path="/" /> <Route path="/customer" render={() => ( <Customer new={this.state.new_customer} callbackRequest={(id, custname) => { this.setCustomer(id, custname); }} customerDetail={this.state.editCustomer} /> )} /> <Route path="/list"> <List /> </Route> <Route path="/item" render={() => ( <Item new={this.state.new_item} refreshItem={() => { this.refreshItem(); }} itemDetail={this.state.editItem} /> )} /> </Switch> </> ); } } export default withRouter(POS); |
index.css
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 | .main-pos-left { background-color: #ffffff; height: 100%; padding: 15px; } .main-pos-right { background-color: #ffffff; height: 100%; padding: 15px; } .main-pos { height: 100%; overflow: auto; } .react-datepicker-popper { z-index: 9999 !important; } .container-header { background-color: #cee2e4; padding: 5px; display: flex; flex-direction: row; } .container-header-1 { width: 145px; } .container-header-2 { flex: 1; } .container-cart { font-size: 14px; } .container-cart .list-group-item { padding: 0.5rem 0.5rem; } .recap-net { font-size: 20px; font-weight: 700; } .cart-name { margin-bottom: 5px; } .cart-detail { font-size: 13px; display: flex; flex-wrap: nowrap; font-style: italic; } .cart-detail > .cart-1 { flex: 1; padding-left: 10px; text-align: left; } .cart-detail > .cart-2 { width: 100px; text-align: right; } .cart-detail > .cart-3 { width: 20px; text-align: right; } .pointer-hand { cursor: pointer; } .container-cart-list { height: 325px; overflow-y: auto; } .container-cart-recap { background-color: #dbdbdb; color: black; } .recap { display: flex; flex-wrap: nowrap; padding: 5px; margin-bottom: 3px; } .recap > .title { flex: 1; } .recap > .result { width: 100px; text-align: right; } .container-cart-list::-webkit-scrollbar { display: none; } /* Hide scrollbar for IE, Edge and Firefox */ .container-cart-list { -ms-overflow-style: none; /* IE and Edge */ scrollbar-width: none; /* Firefox */ } |
At this point, the steps for building the ReactJS simple POS application have been completed. You can test the application by running the command “npm start” in the sample-pos-reactjs folder
preview of ReactJS point of sales application like the following video snippet
Download the Simple POS ReactJS Source Code
Please download the entire ReactJS simple POS code on my Github page
Conclusion
– The main point of using ReactJS is to think in React, Once this is mastered, creating any application using React will become easy.
– Management of application folders is very important, the more complex your application is, the more files it needs. Then the files need to be grouped so that they are easy to use.
– Creating reusable components will speed up application creation.
This is the tutorial for making a simple POS using ReactJS. The application above is still far from expected, but you can modify it according to your needs, such as adding a login page, printing invoices, and so on.
Leave a Reply