magicui-utils
This package provides a collection of useful React hooks and utilities for building UI components.
Table of Contents
Utils Examples
timeAgo
The timeAgo utility function can be used in various scenarios where you want to display the elapsed time since a particular timestamp in a human-readable format.
import { timeAgo } from "magicui-utils";
const timestamp1 = new Date("2023-05-18T10:30:00Z");
console.log(timeAgo(timestamp1));
console.log(timeAgo(timestamp1, { withAgo: true }));
const timestamp2 = new Date("2023-05-15T09:00:00Z");
console.log(timeAgo(timestamp2));
console.log(timeAgo(timestamp2, { withAgo: true }));
const timestamp3 = new Date();
setTimeout(() => {
console.log(timeAgo(timestamp3));
console.log(timeAgo(timestamp3, { withAgo: true }));
}, 500);
const timestamp4 = new Date("2022-08-10T14:45:00Z");
console.log(timeAgo(timestamp4));
console.log(timeAgo(timestamp4, { withAgo: true }));
const timestamp5 = null;
console.log(timeAgo(timestamp5));
console.log(timeAgo(timestamp5, { withAgo: true }));
calculate
import { calculate } from "magicui-utils";
const result1 = calculate("2 + 3 * 4");
console.log(result1);
const result2 = calculate("(2 + 3) * 4");
console.log(result2);
const result3 = calculate("10 / (2 + 3)");
console.log(result3);
class Name
import React from "react";
import { cn } from "magicui-utils";
const App = ({ isActive, className }) => {
const containerClasses = cn("container", {
"is-active": isActive,
"has-border": true,
});
return <div className={cn(containerClasses, className)}>...</div>;
};
datetime
import {
getDateTimeLocal,
parseDateTime,
formatDate,
formatDateTime,
getFirstAndLastDay,
getLastDayOfMonth,
getAdjustedBillingCycleStart,
getBillingStartDate,
} from "magicui-utils";
getDateTimeLocal
This function takes an optional timestamp parameter of type Date and returns a string representation of the date and time in the local time zone.
Example:
const timestamp = new Date("2023-06-10T12:30:00Z");
const localDateTime = getDateTimeLocal(timestamp);
console.log(localDateTime);
parseDateTime
This function takes a str parameter of type Date or string and returns a Date object. If the input is already a Date object, it is returned as is. If the input is a string, it is parsed using the chrono-node library.
const dateString = "2023-06-10";
const date = parseDateTime(dateString);
console.log(date);
formatDate
This function takes a datetime parameter of type Date
or string and returns a formatted date string in the format
"Month Day, Year".
const datetime = new Date("2023-06-10T12:30:00Z");
const formattedDate = formatDate(datetime);
console.log(formattedDate);
formatDateTime
This function takes a datetime
parameter of type Date or string and returns a formatted date and time string in the format "Mon Day, Year, HH:MM AM/PM".
const datetime = new Date("2023-06-10T12:30:00Z");
const formattedDateTime = formatDateTime(datetime);
console.log(formattedDateTime);
getFirstAndLastDay
This function takes a day parameter of type number representing a day of the month and returns an object with the firstDay and lastDay properties. The firstDay represents the first occurrence of the specified day in the current or previous month, and the lastDay represents the last occurrence of the specified day in the current or next month.
const day = 15;
const { firstDay, lastDay } = getFirstAndLastDay(day);
console.log(firstDay);
console.log(lastDay);
getLastDayOfMonth
This function returns the last day of the current month as a number.
const lastDay = getLastDayOfMonth();
console.log(lastDay);
getAdjustedBillingCycleStart
This function takes a billingCycleStart
parameter of type number representing the billing cycle start day and returns an adjusted billing cycle start day based on the number of days in the current month. If the billing cycle start day is greater than the last day of the month, it is adjusted to the last day of the month.
const billingCycleStart = 31;
const adjustedBillingCycleStart =
getAdjustedBillingCycleStart(billingCycleStart);
console.log(adjustedBillingCycleStart);
getBillingStartDate
This function takes a billingCycleStart
parameter of type number
representing the billing cycle start day and returns a Date object representing the billing start date based on the current date and the billing cycle start day.
const billingCycleStart = 15;
const billingStartDate = getBillingStartDate(billingCycleStart);
console.log(billingStartDate);
deepMerge
This utility function
, named deepMerge, performs a deep merge of two or more objects. It recursively merges
the properties of the source objects into the target object, creating a new object that combines all the properties.
import { deepMerge } from "@/utils/deepMerge";
const obj1 = {
a: 1,
b: {
c: 2,
d: 3,
},
};
const obj2 = {
b: {
d: 4,
e: 5,
},
f: 6,
};
const mergedObj = deepMerge(obj1, obj2);
console.log(mergedObj);
groupBy
This utility function, named groupBy
, allows you to group an array of objects based on a specified key or a key function. It returns an object where the keys are the unique values of the specified key, and the values are arrays of objects that have the corresponding key value.
import { groupBy } from "@/utils/groupBy";
interface Person {
name: string;
age: number;
city: string;
}
const people: Person[] = [
{ name: "Alice", age: 25, city: "New York" },
{ name: "Bob", age: 30, city: "London" },
{ name: "Charlie", age: 25, city: "New York" },
{ name: "David", age: 35, city: "London" },
{ name: "Eve", age: 30, city: "Paris" },
];
const groupedByAge = groupBy(people, (person) => person.age);
console.log(groupedByAge);
const groupedByCity = groupBy(people, (person) => person.city);
console.log(groupedByCity);
nFormatter
The nFormatter function is a utility function that formats a number with abbreviations (e.g., 1.2K, 3.5M, 1.2B) for better readability, especially when dealing with large numbers.
import { nFormatter } from "magicui-utils";
console.log(nFormatter(1234));
console.log(nFormatter(12345678, { digits: 2 }));
console.log(nFormatter(123456789012, { full: true }));
nanoid
The nanoid
function is a utility function that generates a unique, secure, URL-friendly, and case-sensitive string identifier. It is a wrapper around the customAlphabet
function from the nanoid
library.
import { nanoid } from "magicui-utils";
console.log(nanoid());
console.log(nanoid(10));
Time Ago
The `timeAgo`` function is a utility function that formats a given timestamp as a human-readable string representing how much time has passed since that timestamp. It provides options to display the time difference with or without the "ago" suffix.
import { timeAgo } from "magicui-utils";
console.log(timeAgo(null));
console.log(timeAgo(new Date()));
console.log(timeAgo(new Date(Date.now() - 60 * 1000)));
console.log(
timeAgo(new Date(Date.now() - 24 * 60 * 60 * 1000), { withAgo: true })
);
console.log(timeAgo(new Date(2023, 0, 1)));
console.log(timeAgo(new Date(2022, 0, 1)));
Trim
The trim
function is a utility function that trims whitespace from the beginning and end of a string. If the input is not a string, it returns the input as-is.
import { trim } from "magicui-utils";
const userInput = " hello@example.com ";
const trimmedEmail = trim(userInput);
console.log(trimmedEmail);
const formData = {
name: " John Doe ",
age: " 30 ",
address: " 123 Main St. ",
};
const cleanedFormData = {
name: trim(formData.name),
age: trim(formData.age),
address: trim(formData.address),
};
console.log(cleanedFormData);
const number = 42;
const trimmedNumber = trim(number);
console.log(trimmedNumber);
Truncate
The truncate
function is a utility function that truncates a given string to a specified length and adds an ellipsis (...) at the end if the string is longer than the specified length.
import { truncate } from "magicui-utils";
console.log(truncate("Hello, World!", 7));
console.log(truncate("This is a long string", 10));
console.log(truncate("Short", 10));
console.log(truncate(null, 5));
console.log(truncate(undefined, 5));
isValidUrl
The isValidUrl function checks whether a given string is a valid URL.
import { isValidUrl } from "magicui-utils";
console.log(isValidUrl("https://example.com"));
console.log(isValidUrl("invalid-url"));
getUrlFromString
The function returns the input string if it is a valid URL. If the input string contains a dot (.) and no spaces, it tries to create a valid URL by prepending https:// to the string. If the input string is not a valid URL and cannot be converted to one, it returns an empty string.
import { getUrlFromString } from "magicui-utils";
console.log(getUrlFromString("https://example.com"));
console.log(getUrlFromString("example.com"));
console.log(getUrlFromString("invalid url"));
getSearchParams
The getSearchParams function retrieves the search parameters from a given URL as a key-value object.
import { getSearchParams } from "magicui-utils";
console.log(getSearchParams("https://example.com?foo=bar&baz=qux"));
console.log(getSearchParams("https://example.com"));
getSearchParamsWithArray
The function returns an object containing the search parameters as key-value pairs. If a key appears multiple times, its value is stored as an array. If the URL is invalid or has no search parameters, it returns an empty object.
import { getSearchParamsWithArray } from "magicui-utils";
console.log(getSearchParamsWithArray("https://example.com?foo=bar&foo=baz"));
console.log(getSearchParamsWithArray("https://example.com?foo=bar&baz=qux"));
console.log(getSearchParamsWithArray("https://example.com"));