JSPM

  • Created
  • Published
  • Downloads 38
  • Score
    100M100P100Q75520F
  • License MIT

A powerful and efficient React utility library designed to enhance application performance by streamlining and simplifying the management of complex asynchronous operations.

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.

Note: This package is written in TypeScript and offers full support for all modern browsers.

Installation

Install the package:

npm install react-js-plugins
# or
yarn add react-js-plugins
# or
pnpm add react-js-plugins

Browser Support

Firefox Chrome Safari Opera Edge
Latest ✔ Latest ✔ Latest ✔ Latest ✔ Latest ✔

Features

Here's the properly structured documentation with clear purpose explanations:

_alert Shows a customizable alert modal. ts // 🚨 Alert Dialog await _alert({ title: "Delete Item?", text: "This action cannot be undone." });

_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. ts const decoded = _decodeURI('hello%20world%402024'); // Output: 'hello world@2024'

_encryptJson
Encrypts a JSON object using AES encryption with a secret key. ts // 🔐 Encrypt JSON const encrypted = _encryptJson({ name: "John" }, "secret123");

_decryptJson
Decrypts AES-encrypted JSON string using a secret key. ts // 🔓 Decrypt JSON const decrypted = _decryptJson(encryptedString, "secret123");

_encryptString
Encrypts a plain string using AES encryption, with optional random IV. ts // 🔐 Encrypt String const result = _encryptString("mySecretText", "secretKey");

_decryptString
Decrypts an AES-encrypted string using the provided IV and secret key. ts // 🔓 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. ts // 🔐 Encrypt Payload const payload = _encryptPayload({ id: 1 }, "mainSecretKey");

_downloadBlob
Triggers download of a Blob object. ts _downloadBlob(blob, 'myfile.pdf');

_fileToBase64
Converts a file to a base64-encoded string.
ts const base64 = await _fileToBase64(file);

_base64ToBlob
Converts a base64-encoded string into a Blob object.
ts const blob = _base64ToBlob(base64String);

_dynamicReducer
Creates a simple dynamic reducer using generic action handler logic. ts // 🧠 Dynamic Reducer const reducer = _dynamicReducer(initialState);

_genericReducer
A generic reducer accepting predefined handlers for each action type. ts // ⚙️ Generic Reducer with Custom Actions const reducer = _genericReducer(initialState, customActions);

_exportExcel
Exports JSON data to an Excel or CSV file.

  const sampleData = [
    { name: 'Siya', age: 30 },
    { name: 'Riya', age: 25 },
  ];

  _exportExcel({
    data: sampleData,
    filename: 'UserData',
    extension: '.xlsx',
  })
  .then((res) => {
    console.log('Export success:', res);
  })
  .catch((err) => {
    console.error('Export failed:', err);
  });

_importExcel
Exports JSON data to an Excel file.

// 📤 Import to Excel
const fileInputHandler = async (event: React.ChangeEvent<HTMLInputElement>) => {
  const { data, error } = await _importExcel(event);

  if (error) {
    console.error('Error:', error.message);
    return;
  }
  
  if (data) {
    console.log('Successfully parsed data:', data);
  }
};

_thousandSeparator
Formats a number with thousand separators and fixed decimal precision. ts // 💰 Thousand Separator const formatted = _thousandSeparator(1234567.89);

_getFinancialYear
Returns the current financial year based on today's date. ts // 📆 Get Financial Year const fy = _getFinancialYear();

_dateFormat
Formats a date using Moment.js with the specified format.
ts const formatted = _dateFormat(new Date(), 'YYYY-MM-DD');

_dateTransformer
Recursively formats all dates in an object or array.

const result = _dateTransformer(data);

_getStorage
Handles local/session storage actions like GET, SET, REMOVE, CLEAR. ts // 🗃️ Use Local Storage const data = _getStorage({ action: 'GET', type: 'local', key: 'user' });

_convertToCurrency
Converts a number to a formatted currency string. ts // 💵 Convert to Currency const price = _convertToCurrency(2500, 'INR');

_parseJSON
Safely parses a JSON string into an object. ts // 📦 Parse JSON const obj = _parseJSON(jsonString);

_stringifyJSON
Safely converts an object to a JSON string.

// 🧾 Stringify JSON
const str = _stringifyJSON(obj);

_getBrowserInfo
Returns the name of the browser (e.g., Chrome, Firefox). ts // 🌐 Get Browser Info const browser = _getBrowserInfo();

_generatePassword
Generates a strong random password with mixed characters. ts // 🔑 Generate Random Password const newPassword = _generatePassword(12);

_getStartStopTime
Returns the start and end datetime of a given date's month in specified format. ts // 🕐 Get Start & Stop Time const { startTime, stopTime } = _getStartStopTime(new Date());

getUTCTimestamp
Returns the UTC timestamp. ts const ts3 = getUTCTimestamp({ year: 2025, month: "December", day: 25, hour: 10, minute: 30 }); console.log(new Date(ts3).toUTCString()); // Thu, 25 Dec 2025 10:30:00 GMT

_setTouchedFields
Marks all fields with errors as touched in a Formik form.
ts _setTouchedFields(formRef, errors);

_isValidForm
Validates a Formik form and returns whether it's valid.
ts const isValid = await _isValidForm(formRef);

_validateFormRef
Returns form validity and error details from a Formik ref.
ts const { isValid, errors } = await _validateFormRef(formRef);

_initializeFormValues
Initializes form values with empty strings for each field.
ts const initialValues = _initializeFormValues(['name', 'email']);

_dynamicRequiredValidation
Generates a Yup schema with required validations for given fields.
ts const schema = _dynamicRequiredValidation(['name', 'email']);

_generateYupValidation
Creates a Yup validation schema with all fields marked as required.
ts const schema = _generateYupValidation(['name', 'age']);

_initializeFormikFields
Returns an object with default empty string values for Formik fields.
ts const formikFields = _initializeFormikFields(['username', 'password']);

_isEmptyArray
Checks if a given value is an empty array. ts // 📭 Check Empty Array const isEmpty = _isEmptyArray([]);

_isEmptyObject
Checks if an object has no own properties. ts // 📭 Check Empty Object const isObjEmpty = _isEmptyObject({});

_isValueInArray
Checks whether a value exists in a given array. ts // 🔍 Value in Array const exists = _isValueInArray([1, 2, 3], 2);

_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. ts // 🧭 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. ts // 🔎 Find Element in Menu const found = _hasElement(menuItems, "id", 5);

_flattenArray
Flattens nested arrays by recursively extracting item.data if present. ts // 🔁 Flatten Nested Arrays const flat = _flattenArray(nestedArray);

_deepClone
Deep clones an object using JSON.stringify and JSON.parse. ts // 🧬 Deep Clone const clone = _deepClone(originalObj);

_mergeObjects
Merges two objects, giving priority to the second object’s properties. ts // 🔀 Merge Objects const merged = _mergeObjects(obj1, obj2);

_mapObject
Maps over an object and returns an array using a callback. ts // 🗺️ Map Object const result = _mapObject(myObj, (key, value) => `${key}: ${value}`);

_isEqual
Checks deep equality of two values using JSON.stringify. ts // 🟰 Check Equality const isSame = _isEqual(obj1, obj2);

_capitalize
Capitalizes the first character of a string. ts // 🔡 Capitalize const name = _capitalize("john");

_isMobile
Detects if the current device is a mobile device. ts // 📱 Check if Mobile const mobile = _isMobile();

_scrollToTop
Scrolls the page smoothly to the top. ts // ⬆️ Scroll to Top _scrollToTop();

_batchProcess
Processes an array of data in asynchronous batches. ts await _batchProcess(myArray, 10, async (item) => { await handleItem(item); });

_flattenObject
Flattens a nested object into dot notation key-value pairs. ts const flat = _flattenObject({ a: { b: 1 } }); // { 'a.b': 1 }

_deepMerge
Recursively merges two objects. ts 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. ts const debouncedFn = _asyncDebounce(fetchData, 500); debouncedFn();

_deepCloneArray
Deeply clones an array of objects. ts const cloned = _deepCloneArray(originalArray);

_getMaxMinValue
Finds the max and min values in an array. ts const { max, min } = _getMaxMinValue([5, 2, 9]);

_asyncMap
Async map over array items one by one. ts 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. ts const value = _getNestedProperty(user, 'profile.name');

_deepEqual
Deep comparison between two objects. ts const isSame = _deepEqual(objA, objB);

_mergeArrays
Merges two arrays and removes duplicates. ts const merged = _mergeArrays(arr1, arr2);

_filterDuplicates
Removes duplicates based on a specific object key. ts const unique = _filterDuplicates(users, 'id');

_sortByKey
Sorts array of objects by a specific key. ts const sorted = _sortByKey(products, 'price');

_mapAsync
Parallel async map over array. ts const data = await _mapAsync(users, fetchDetails);

_formatDate
Formats a date based on a custom pattern. ts _formatDate(new Date(), 'YMD'); // e.g., "Apr 9, 2025"

_calPercentage
Calculates the percentage of a value relative to total. ts _calPercentage(40, 200); // 20

_sum
Returns the sum of an array of numbers. ts _sum([1, 2, 3]); // 6

_average
Calculates the average of numbers in an array. ts _average([4, 8]); // 6

_getPriceAfterTax
Adds tax to a given price. ts _getPriceAfterTax(100, 18); // 118

_calculateTimeDifference
Returns difference between two dates in readable format. ts _calculateTimeDifference(start, end); // "1d 2h 3m 4s"

_arrayIncludesObject
Checks if array contains object (by value). ts _arrayIncludesObject(arr, obj);

_toCamelCase
Converts kebab-case or snake_case to camelCase. ts _toCamelCase('hello_world'); // helloWorld

_freeze
Freezes an object to make it immutable. ts const frozen = _freeze(config);

_isFreeze
Checks if object is frozen. ts _isFreeze(obj); // true/false

_seal
Seals an object to prevent adding/removing properties. ts _seal(settings);

_isSeal
Checks if object is sealed. ts _isSeal(obj); // true/false

_arrayToObject
Converts array of key-value pairs to object. ts _arrayToObject([['a', 1], ['b', 2]]);

_objectToArray
Converts object to array of key-value pairs. ts _objectToArray({ a: 1 }); // [['a', 1]]

_arrayToObjectByKey
Converts array of objects to object using a key. ts _arrayToObjectByKey(users, 'id');

_isInArray
Checks if a value exists in array. ts _isInArray(['a', 'b'], 'b'); // true

_getObjectValues
Returns object values as an array. ts _getObjectValues({ a: 1, b: 2 }); // [1, 2]

_swapArrayElements
Swaps two elements in an array. ts _swapArrayElements(arr, 0, 1);

_filterObjectByKey
Filters object based on allowed keys. ts _filterObjectByKey(user, ['id', 'name']);

_getScrollPosition
Returns current window scroll position.

const { scrollX, scrollY } = _getScrollPosition();

_arrayIntersection
Returns common elements between two arrays. ts _arrayIntersection([1,2,3], [2,3,4]); // [2,3]

_getArrayOfObjectsByProperty
Returns all objects with a specific property value. ts _getArrayOfObjectsByProperty(data, 'type', 'active');

_setNestedProperty
Sets a deeply nested property in an object using a string path.
ts _setNestedProperty(obj, 'user.address.city', 'Mumbai');

_transformArray
Applies a transformation function to each item in an array.
ts const result = _transformArray(users, user => user.name);

_findObjectById
Finds an object in an array by its id.
ts const item = _findObjectById(items, '123');

_getUniqueValues
Returns an array of unique values.
ts 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');

_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');

_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);

_domSelector
Selects a single or all DOM elements matching a CSS selector.

// 🔍 Select DOM Element
const el = _domSelector('#myElement');

// 🔍 Select All DOM Elements
const elements = _domSelector('.list-item', true);

_hideElement
Hides a DOM element by setting its display style to 'none'.

// 🙈 Hide Element
_hideElement('#modal');

_showElement
Displays a hidden DOM element using the provided displayType (default is 'block').

// 👁️ Show Element
_showElement('#modal');

// 👁️ Show with Custom Display Type
_showElement('#modal', 'flex');

_removeElement
Removes the first matched DOM element from the document.

// ❌ Remove Element
_removeElement('#banner');

_removeNode
Removes all matched DOM elements from the document.

// 🧹 Remove All Matching Nodes
_removeNode('.temp-item');

_removeSafeElement
Safely removes an element if it exists and has a parent.

// 🛡️ Safe Remove Element
_removeSafeElement('#popup');

_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. ts const exists = _isElementPresent('.my-element');

_removeElement
Removes an element from the DOM.

_removeElement('#to-remove');

_getParent
Returns parent of a DOM element. ts const parent = _getParent('.child');

_getChildElements
Returns child elements of a selector. ts const children = _getChildElements('.container');

_handleParentsMenu
Recursively updates parent menu's assigned state and permissions based on children. ts _handleParentsMenu(menuList, menuId);

_handleParentNode
Recursively updates parent permissions based on child permissions. ts _handleParentNode(menuList, menuId, permissionKey);

_handleChildrenMenu
Recursively sets assigned state and permissions of child nodes.

_handleChildrenMenu(menuList, parentKey, checked);

_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());

✏️ Authors

NPM   npm   npm   NPM   NPM Unpacked Size

License

MIT