@bithero/react-helpers
TypeScript icon, indicating that this package has built-in type declarations

1.1.2 • Public • Published

react-helpers

Npm package version Npm package license Npm package types

Collection of usefull functions, hooks, and so on to aid development of react based apps.

License

This project is licensed under AGPL-3.0. See the LICENSE file for more informations.

Usage

classNames

import { classNames } from '@bithero/react-helpers';

/*
    The `classNames()` helper function aids in programatic "generation" of html/css classnames
    by providing an simple way to use the ternary operator to switch between classnames.
*/
classNames([ "some-class", true  ? "visible": null ]);  // ==> "some-class visible"
classNames([ "some-class", false ? "visible": null ]);  // ==> "some-class"

useControlled

import { useControlled } from '@bithero/react-helpers';

/*
    With `useControlled()` one can build components that are either controlled or uncontrolled:
*/
interface IMySelectProps extends React.HTMLAttributes<HTMLElement> {
    selection?: string
    onSelectionChange?(selection: string)
}

export const MySelect = ({ selection: controlledSelection, onSelectionChange }: IMySelectProps) => {

    // useControlled() uses useState() internally, but only if `controlled` is not `undefined`;
    const [ selection, setSelection ] = useControlled<string>({
        controlled: controlledSelection,
        default: null,
        name: 'MySelect.selection'
    });

    const isControlled = controlledSelection !== undefined;

    const changeSelection = (selection: string) => {
        if (!isControlled) {
            setSelection(selection);
        }
        onSelectionChange?.(selection);
    }

    return ( /* ... */ );
}

hookAware callbacks

import { IHookAware, createHookAware, CallbackOrHookAware, setupHookAware, runHookAware } from '@bithero/react-helpers';

export function MyComponent({ cb }: { cb: CallbackOrHookAware<(a: number, b: number) => number> }) {
    const hookValues = setupHookAware(cb);

    useEffect(() => {
        var c: number = runHookAware(cb, hookValues, 5, 12);
    }, [cb, hookValues])

    return (<div></div>);
}

export function MyOtherComponent() {
    const handler: IHookAware<(a: number, b: number) => number> = createHookAware(
        {'zState': [useState, 0]},
        function (a, b) {
            const [z, setZ] = this.zState;
            return a + b;
        }
    );
    return (<MyComponent cb={handler}/>);
}

export function MyThirdComponent() {
    const handler = (a: number, b: number) => (a + b);
    return (<MyComponent cb={handler}/>);
}

Package Sidebar

Install

npm i @bithero/react-helpers

Weekly Downloads

6

Version

1.1.2

License

AGPL-3.0-or-later

Unpacked Size

48.8 kB

Total Files

13

Last publish

Collaborators

  • mai-lapyst