Package Exports
- react-js-plugins
- react-js-plugins/dist/index.js
This package does not declare an exports field, so the exports above have been automatically detected and optimized by JSPM instead. If any package subpath is missing, it is recommended to post an issue to the original package (react-js-plugins) to support the "exports" field. If that is not possible, create a JSPM override to customize the exports field for this package.
Readme
react-js-plugins package is a lightweight and powerful toolkit for developers, providing reusable solutions for various application requirements. react-js-plugins offers a comprehensive collection of utility functions designed to simplify common development tasks. Key functionalities include form validation, date formatting, array/object manipulation, and exporting data to Excel. Additional features include browser/device detection, storage management, reducers, performance optimization utilities, and string/number formatting tools. Install it via npm i react-js-plugins to streamline your development workflow.
Installation
Install the package:
npm install react-js-plugins
# or
yarn add react-js-plugins
# or
pnpm add react-js-plugins
Features
Here's the properly structured documentation with clear purpose explanations:
✅ _encodeURI
Encodes a URI component by escaping special characters to make it safe for use in URLs.
const encoded = _encodeURI('hello world@2024');
// Output: 'hello%20world%402024'
✅ _decodeURI
Decodes an encoded URI component back to its original readable string format.
const decoded = _decodeURI('hello%20world%402024');
// Output: 'hello world@2024'
✅ _alert
Shows a customizable alert modal.
// 🚨 Alert Dialog
await _alert({ title: "Delete Item?", text: "This action cannot be undone." });
✅ _encryptJson
Encrypts a JSON object using AES encryption with a secret key.
// 🔐 Encrypt JSON
const encrypted = _encryptJson({ name: "John" }, "secret123");
✅ _decryptJson
Decrypts AES-encrypted JSON string using a secret key.
// 🔓 Decrypt JSON
const decrypted = _decryptJson(encryptedString, "secret123");
✅ _encryptString
Encrypts a plain string using AES encryption, with optional random IV.
// 🔐 Encrypt String
const result = _encryptString("mySecretText", "secretKey");
✅ _decryptString
Decrypts an AES-encrypted string using the provided IV and secret key.
// 🔓 Decrypt String
const plainText = _decryptString(ciphertext, iv, "secretKey");
✅ _encryptPayload
Encrypts a full payload using a randomly generated key and IV, secured by a static key.
// 🔐 Encrypt Payload
const payload = _encryptPayload({ id: 1 }, "mainSecretKey");
✅ _generatePassword
Generates a strong random password with mixed characters.
// 🔑 Generate Random Password
const newPassword = _generatePassword(12);
✅ _getStartStopTime
Returns the start and end datetime of a given date's month in specified format.
// 🕐 Get Start & Stop Time
const { startTime, stopTime } = _getStartStopTime(new Date());
✅ _isEmptyArray
Checks if a given value is an empty array.
// 📭 Check Empty Array
const isEmpty = _isEmptyArray([]);
✅ _isEmptyObject
Checks if an object has no own properties.
// 📭 Check Empty Object
const isObjEmpty = _isEmptyObject({});
✅ _isValueInArray
Checks whether a value exists in a given array.
// 🔍 Value in Array
const exists = _isValueInArray([1, 2, 3], 2);
✅ _exportToExcel
Exports JSON data to an Excel file.
// 📤 Export to Excel
_exportToExcel([{ name: "John" }], "UserList");
✅ _promise
Creates a delay for a given time using Promise.
// ⏳ Delay Execution
await _promise(1000); // 1 second delay
✅ _hasItem
Searches recursively in a menu tree to find an item by path
.
// 🧭 Find Menu Item by Path
const item = _hasItem(menuItems, "/dashboard");
✅ _hasElement
Searches recursively in a menu tree to find an element by key and value.
// 🔎 Find Element in Menu
const found = _hasElement(menuItems, "id", 5);
✅ _flattenArray
Flattens nested arrays by recursively extracting item.data
if present.
// 🔁 Flatten Nested Arrays
const flat = _flattenArray(nestedArray);
✅ _dynamicReducer
Creates a simple dynamic reducer using generic action handler logic.
// 🧠 Dynamic Reducer
const reducer = _dynamicReducer(initialState);
✅ _genericReducer
A generic reducer accepting predefined handlers for each action type.
// ⚙️ Generic Reducer with Custom Actions
const reducer = _genericReducer(initialState, customActions);
✅ _thousandSeparator
Formats a number with thousand separators and fixed decimal precision.
// 💰 Thousand Separator
const formatted = _thousandSeparator(1234567.89);
✅ _getFinancialYear
Returns the current financial year based on today's date.
// 📆 Get Financial Year
const fy = _getFinancialYear();
✅ _getStorage
Handles local/session storage actions like GET, SET, REMOVE, CLEAR.
// 🗃️ Use Local Storage
const data = _getStorage({ action: 'GET', type: 'local', key: 'user' });
✅ _deepClone
Deep clones an object using JSON.stringify
and JSON.parse
.
// 🧬 Deep Clone
const clone = _deepClone(originalObj);
✅ _getCookie
Retrieves a cookie value by its name.
// 🍪 Get Cookie
const token = _getCookie('auth_token');
✅ _setCookie
Sets a cookie with a name, value, and expiry (in days).
// 📝 Set Cookie
_setCookie('auth_token', 'abc123', 7);
✅ _mergeObjects
Merges two objects, giving priority to the second object’s properties.
// 🔀 Merge Objects
const merged = _mergeObjects(obj1, obj2);
✅ _mapObject
Maps over an object and returns an array using a callback.
// 🗺️ Map Object
const result = _mapObject(myObj, (key, value) => `${key}: ${value}`);
✅ _isEqual
Checks deep equality of two values using JSON.stringify
.
// 🟰 Check Equality
const isSame = _isEqual(obj1, obj2);
✅ _capitalize
Capitalizes the first character of a string.
// 🔡 Capitalize
const name = _capitalize("john");
✅ _convertToCurrency
Converts a number to a formatted currency string.
// 💵 Convert to Currency
const price = _convertToCurrency(2500, 'INR');
✅ _getBrowserInfo
Returns the name of the browser (e.g., Chrome, Firefox).
// 🌐 Get Browser Info
const browser = _getBrowserInfo();
✅ _isMobile
Detects if the current device is a mobile device.
// 📱 Check if Mobile
const mobile = _isMobile();
✅ _parseJSON
Safely parses a JSON string into an object.
// 📦 Parse JSON
const obj = _parseJSON(jsonString);
✅ _stringifyJSON
Safely converts an object to a JSON string.
// 🧾 Stringify JSON
const str = _stringifyJSON(obj);
✅ _scrollToTop
Scrolls the page smoothly to the top.
// ⬆️ Scroll to Top
_scrollToTop();
✅ _batchProcess
Processes an array of data in asynchronous batches.
await _batchProcess(myArray, 10, async (item) => {
await handleItem(item);
});
✅ _flattenObject
Flattens a nested object into dot notation key-value pairs.
const flat = _flattenObject({ a: { b: 1 } }); // { 'a.b': 1 }
✅ _deepMerge
Recursively merges two objects.
const merged = _deepMerge(obj1, obj2);
✅ _chunk
Splits an array into chunks of a given size.
const parts = _chunk([1, 2, 3, 4], 2); // [[1,2], [3,4]]
✅ _asyncDebounce
Debounces an async function call.
const debouncedFn = _asyncDebounce(fetchData, 500);
debouncedFn();
✅ _deepCloneArray
Deeply clones an array of objects.
const cloned = _deepCloneArray(originalArray);
✅ _getMaxMinValue
Finds the max and min values in an array.
const { max, min } = _getMaxMinValue([5, 2, 9]);
✅ _asyncMap
Async map over array items one by one.
const results = await _asyncMap(ids, fetchById);
✅ _transformAsyncData
Applies a transformer to each array item asynchronously.
const updated = await _transformAsyncData(data, transformFn);
✅ _getNestedProperty
Retrieves value from object using a string path.
const value = _getNestedProperty(user, 'profile.name');
✅ _deepEqual
Deep comparison between two objects.
const isSame = _deepEqual(objA, objB);
✅ _mergeArrays
Merges two arrays and removes duplicates.
const merged = _mergeArrays(arr1, arr2);
✅ _filterDuplicates
Removes duplicates based on a specific object key.
const unique = _filterDuplicates(users, 'id');
✅ _sortByKey
Sorts array of objects by a specific key.
const sorted = _sortByKey(products, 'price');
✅ _mapAsync
Parallel async map over array.
const data = await _mapAsync(users, fetchDetails);
✅ _formatDate
Formats a date based on a custom pattern.
_formatDate(new Date(), 'YMD'); // e.g., "Apr 9, 2025"
✅ _calPercentage
Calculates the percentage of a value relative to total.
_calPercentage(40, 200); // 20
✅ _sum
Returns the sum of an array of numbers.
_sum([1, 2, 3]); // 6
✅ _average
Calculates the average of numbers in an array.
_average([4, 8]); // 6
✅ _getPriceAfterTax
Adds tax to a given price.
_getPriceAfterTax(100, 18); // 118
✅ _calculateTimeDifference
Returns difference between two dates in readable format.
_calculateTimeDifference(start, end); // "1d 2h 3m 4s"
✅ _arrayIncludesObject
Checks if array contains object (by value).
_arrayIncludesObject(arr, obj);
✅ _toCamelCase
Converts kebab-case or snake_case to camelCase.
_toCamelCase('hello_world'); // helloWorld
✅ _freeze
Freezes an object to make it immutable.
const frozen = _freeze(config);
✅ _isFreeze
Checks if object is frozen.
_isFreeze(obj); // true/false
✅ _seal
Seals an object to prevent adding/removing properties.
_seal(settings);
✅ _isSeal
Checks if object is sealed.
_isSeal(obj); // true/false
✅ _arrayToObject
Converts array of key-value pairs to object.
_arrayToObject([['a', 1], ['b', 2]]);
✅ _objectToArray
Converts object to array of key-value pairs.
_objectToArray({ a: 1 }); // [['a', 1]]
✅ _arrayToObjectByKey
Converts array of objects to object using a key.
_arrayToObjectByKey(users, 'id');
✅ _isInArray
Checks if a value exists in array.
_isInArray(['a', 'b'], 'b'); // true
✅ _getObjectValues
Returns object values as an array.
_getObjectValues({ a: 1, b: 2 }); // [1, 2]
✅ _swapArrayElements
Swaps two elements in an array.
_swapArrayElements(arr, 0, 1);
✅ _filterObjectByKey
Filters object based on allowed keys.
_filterObjectByKey(user, ['id', 'name']);
✅ _getScrollPosition
Returns current window scroll position.
const { scrollX, scrollY } = _getScrollPosition();
✅ _arrayIntersection
Returns common elements between two arrays.
_arrayIntersection([1,2,3], [2,3,4]); // [2,3]
✅ _getArrayOfObjectsByProperty
Returns all objects with a specific property value.
_getArrayOfObjectsByProperty(data, 'type', 'active');
✅ _downloadBlob
Triggers download of a Blob object.
_downloadBlob(blob, 'myfile.pdf');
✅ _fileToBase64
Converts a file to a base64-encoded string.
const base64 = await _fileToBase64(file);
✅ _base64ToBlob
Converts a base64-encoded string into a Blob object.
const blob = _base64ToBlob(base64String);
✅ _initializeFormValues
Initializes form values with empty strings for each field.
const initialValues = _initializeFormValues(['name', 'email']);
✅ _dynamicRequiredValidation
Generates a Yup schema with required validations for given fields.
const schema = _dynamicRequiredValidation(['name', 'email']);
✅ _generateYupValidation
Creates a Yup validation schema with all fields marked as required.
const schema = _generateYupValidation(['name', 'age']);
✅ _initializeFormikFields
Returns an object with default empty string values for Formik fields.
const formikFields = _initializeFormikFields(['username', 'password']);
✅ _setNestedProperty
Sets a deeply nested property in an object using a string path.
_setNestedProperty(obj, 'user.address.city', 'Mumbai');
✅ _transformArray
Applies a transformation function to each item in an array.
const result = _transformArray(users, user => user.name);
✅ _findObjectById
Finds an object in an array by its id
.
const item = _findObjectById(items, '123');
✅ _getUniqueValues
Returns an array of unique values.
const unique = _getUniqueValues([1, 2, 2, 3]);
✅ _mergeArraysByKey
Merges two arrays of objects based on a common key.
const merged = _mergeArraysByKey(arr1, arr2, 'id');
✅ _removeDuplicates
Removes duplicate objects based on a key.
const cleaned = _removeDuplicates(data, 'email');
✅ _groupBy
Groups array items by a given key.
const grouped = _groupBy(users, 'department');
✅ _arrayDiff
Returns the difference between two arrays.
const diff = _arrayDiff(['a', 'b'], ['b']);
✅ _deepCompareArrays
Checks if two arrays are deeply equal.
const isEqual = _deepCompareArrays(arr1, arr2);
✅ _updateObjectInArray
Updates a matching object in an array by key-value.
const updated = _updateObjectInArray(users, 'id', '123', { name: 'New Name' });
✅ _getKeyByValue
Returns the first key in an object with the matching value.
const key = _getKeyByValue(obj, 'targetValue');
✅ _getValueByKey
Returns the value of a key from an object.
const value = _getValueByKey(obj, 'username');
✅ _getKeysByValue
Finds all keys in an object with a specific value.
const keys = _getKeysByValue(obj, 'active');
✅ _dateFormat
Formats a date using Moment.js with the specified format.
const formatted = _dateFormat(new Date(), 'YYYY-MM-DD');
✅ _dateTransformer
Recursively formats all dates in an object or array.
const result = _dateTransformer(data);
✅ _escapeRegExpMatch
Escapes special characters for regex matching.
const escaped = _escapeRegExpMatch('a+b*c');
✅ _isExactMatch
Checks if a string contains an exact word match using regex.
const match = _isExactMatch('The quick brown fox', 'quick');
✅ _bytesToSize
Converts byte size into a human-readable format.
const size = _bytesToSize(1024); // "1 KB"
✅ _swapArrayByKey
Sorts an array in descending order based on a key.
const sorted = _swapArrayByKey(data, 'score');
✅ _setTouchedFields
Marks all fields with errors as touched in a Formik form.
_setTouchedFields(formRef, errors);
✅ _isValidForm
Validates a Formik form and returns whether it's valid.
const isValid = await _isValidForm(formRef);
✅ _validateFormRef
Returns form validity and error details from a Formik ref.
const { isValid, errors } = await _validateFormRef(formRef);
✅ _handleParentsMenu
Recursively updates parent menu's assigned state and permissions based on children.
_handleParentsMenu(currentArr, menuID);
✅ _handleParentNode
Recursively updates parent permissions based on child permissions.
_handleParentNode(currentArr, menuID, permissionKey);
✅ _handleChildrenMenu
Recursively sets assigned state and permissions of child nodes.
_handleChildrenMenu(currentArr, parentKey, checked);
✅ _allowDecimalKeys
Allows only decimal input and valid control keys.
<input onKeyDown={_allowDecimalKeys} />
✅ _allowAlphaKeys
Allows only alphabetic input and valid control keys.
<input onKeyDown={_allowAlphaKeys} />
✅ _handlePasteDecimalKeys
Prevents pasting invalid decimal values.
<input onPaste={_handlePasteDecimalKeys} />
✅ _handlePasteAlphabetKeys
Prevents pasting non-alphabetic characters.
<input onPaste={_handlePasteAlphabetKeys} />
✅ _allowAlphaNumericKeys
Allows only alphanumeric keys during typing.
document.addEventListener('keydown', _allowAlphaNumericKeys);
✅ _clearNode
Hides specific sibling DOM nodes relative to a base element.
_clearNode('.my-element', [{ type: 'previous', steps: 1 }]);
✅ _isElementPresent
Checks if an element exists in the DOM.
const exists = _isElementPresent('.my-element');
✅ _removeElement
Removes an element from the DOM.
_removeElement('#to-remove');
✅ _getParent
Returns parent of a DOM element.
const parent = _getParent('.child');
✅ _getChildElements
Returns child elements of a selector.
const children = _getChildElements('.container');
✅ _replaceContent
Replaces inner HTML of an element.
_replaceContent('#content', '<p>New content</p>');
✅ _cloneElement
Clones a DOM element.
const clone = _cloneElement('.to-clone');
✅ _scrollToElement
Scrolls smoothly to an element.
_scrollToElement('#target');
✅ _isElementInViewport
Checks if element is visible in viewport.
const isVisible = _isElementInViewport('.my-element');
✅ _setElementDisabled
Enables or disables a DOM element.
_setElementDisabled('#submit-btn', true);
✅ _addEventListenerToElement
Attaches an event listener to a DOM element.
_addEventListenerToElement('#my-btn', 'click', handleClick);
✅ _removeEventListenerFromElement
Removes a specific event listener.
_removeEventListenerFromElement('#my-btn', 'click', handleClick);
✅ _getElementAttribute
Gets the value of an element’s attribute.
const id = _getElementAttribute('.item', 'data-id');
✅ _setElementAttribute
Sets an attribute on a DOM element.
_setElementAttribute('.item', 'data-id', '123');
✅ _removeElementAttribute
Removes an attribute from an element.
_removeElementAttribute('.item', 'data-id');
✅ _removeAllChildren
Clears all child nodes of an element.
_removeAllChildren('#container');
✅ _getElementsByClass
Returns elements with a given class.
const elements = _getElementsByClass('my-class');
✅ _getElementsByTag
Returns elements with a given tag name.
const buttons = _getElementsByTag('button');
✅ _setMultipleStyles
Applies multiple CSS styles to an element.
_setMultipleStyles('.card', { color: 'red', fontWeight: 'bold' });
✅ _insertHTML
Injects HTML at a specific position.
_insertHTML('#box', 'beforeend', '<div>Hello</div>');
✅ _isDocumentLoaded
Checks if the document has fully loaded.
if (_isDocumentLoaded()) { /* safe to run code */ }
✅ _runOnIframeLoad
Runs a callback when iframe finishes loading.
_runOnIframeLoad('#myIframe', () => console.log('Loaded'));
✅ _reloadAfterLoad
Reloads page after a delay post-load.
_reloadAfterLoad(3000); // Reload 3s after load
✅ _isValidEmail
Checks if a string is a valid email address.
// 📧 Validate Email
const isValid = _isValidEmail('user@example.com');
✅ _isValidPhoneNumber
Checks if a string is a valid international phone number (10–15 digits).
// 📱 Validate Phone Number
const isValid = _isValidPhoneNumber('+919876543210');
✅ _isValidURL
Checks if a string is a valid URL format.
// 🌐 Validate URL
const isValid = _isValidURL('https://example.com');
✅ _isValidDate
Checks if a string matches the YYYY-MM-DD
date format.
// 📅 Validate Date
const isValid = _isValidDate('2025-04-09');
✅ _isValidTime
Checks if a string is a valid 24-hour HH:mm
format.
// ⏰ Validate Time
const isValid = _isValidTime('23:59');
✅ _isValidDateTime
Checks if a string matches the YYYY-MM-DDTHH:mm:ss
format.
// 🕒 Validate DateTime
const isValid = _isValidDateTime('2025-04-09T12:30:00');
✅ _isValidDateRange
Checks if the start date is earlier than or equal to the end date.
// 🔄 Validate Date Range
const isValid = _isValidDateRange('2025-01-01', '2025-12-31');
✅ _isValidPassword
Checks if a password has 8+ characters, at least 1 letter and 1 number.
// 🔐 Validate Password
const isValid = _isValidPassword('Abc12345');
✅ _isValidUsername
Checks if a username is 3+ characters and contains only letters, numbers, dots, underscores, or hyphens.
// 👤 Validate Username
const isValid = _isValidUsername('john_doe');
✅ _isValidCreditCard
Checks if a string matches known credit card patterns.
// 💳 Validate Credit Card
const isValid = _isValidCreditCard('4111111111111111');
✅ _isValidHexColor
Checks if a string is a valid hex color code.
// 🎨 Validate Hex Color
const isValid = _isValidHexColor('#FF5733');
✅ _isValidIP
Checks if a string is a valid IPv4 address.
// 🌐 Validate IP Address
const isValid = _isValidIP('192.168.1.1');
✅ _isValidMacAddress
Checks if a string is a valid MAC address.
// 💻 Validate MAC Address
const isValid = _isValidMacAddress('00:1A:2B:3C:4D:5E');
✅ _isValidUUID
Checks if a string is a valid UUID (v1 to v5).
// 🆔 Validate UUID
const isValid = _isValidUUID('550e8400-e29b-41d4-a716-446655440000');
✅ _isValidBase64
Checks if a string is a valid Base64-encoded value.
// 🧬 Validate Base64
const isValid = _isValidBase64('U29tZSB0ZXh0');
✅ _isValidJSON
Checks if a string is valid JSON.
// 📦 Validate JSON
const isValid = _isValidJSON('{"name":"John"}');
✅ _isValidFunction
Checks if the input is a valid function.
// 🛠️ Validate Function
const isValid = _isValidFunction(() => {});
✅ _isValidString
Checks if the input is a non-empty string.
// ✏️ Validate String
const isValid = _isValidString('Hello');
✅ _isValidNumber
Checks if the input is a valid number.
// 🔢 Validate Number
const isValid = _isValidNumber(123.45);
✅ _isValidBoolean
Checks if the input is a boolean.
// ✅ Validate Boolean
const isValid = _isValidBoolean(true);
✅ _isValidDateObject
Checks if the input is a valid Date
object.
// 📆 Validate Date Object
const isValid = _isValidDateObject(new Date());
✅ _isValidBlob
Checks if the input is a Blob
.
// 🗂️ Validate Blob
const isValid = _isValidBlob(new Blob(['text']));
✅ _isValidFile
Checks if the input is a File
.
// 📁 Validate File
const isValid = _isValidFile(new File([''], 'file.txt'));
✅ _isValidRegExp
Checks if the input is a regular expression.
// 🔍 Validate RegExp
const isValid = _isValidRegExp(/abc/);
✅ _isValidPromise
Checks if the input is a Promise
.
// ⏳ Validate Promise
const isValid = _isValidPromise(Promise.resolve());
✅ _isValidDateString
Checks if the string can be parsed as a valid date.
// 🗓️ Validate Date String
const isValid = _isValidDateString('2025-04-09');
✅ _isValidHTMLElement
Checks if the input is an instance of HTMLElement
.
// 🧱 Validate HTMLElement
const isValid = _isValidHTMLElement(document.body);
✅ _isValidEvent
Checks if the input is an instance of Event
.
// 🎫 Validate Event
const isValid = _isValidEvent(new Event('click'));
✅ _isValidNode
Checks if the input is a Node
.
// 🌿 Validate Node
const isValid = _isValidNode(document.createTextNode('text'));
✅ _isValidNodeList
Checks if the input is a NodeList
.
// 📚 Validate NodeList
const isValid = _isValidNodeList(document.querySelectorAll('div'));
✅ _isValidHTMLCollection
Checks if the input is an HTMLCollection
.
// 🏗️ Validate HTMLCollection
const isValid = _isValidHTMLCollection(document.forms);
✅ _isValidFormData
Checks if the input is a FormData
instance.
// 📝 Validate FormData
const isValid = _isValidFormData(new FormData());
✅ _isValidURLSearchParams
Checks if the input is a URLSearchParams
instance.
// 🔍 Validate URLSearchParams
const isValid = _isValidURLSearchParams(new URLSearchParams());