Options
All
  • Public
  • Public/Protected
  • All
Menu

Module @interface-technologies/iti-react

Index

Classes

Interfaces

Type aliases

Variables

Functions

Type aliases

AddressInputFieldLengths

AddressInputFieldLengths: { city: number; line1: number; line2: number }

The field lengths required by AddressInput.

Type declaration

  • city: number
  • line1: number
  • line2: number

AddressInputValue

AddressInputValue: { city: string; line1: string; line2: string; postalCode: string; state: string }

The value type for AddressInput.

Type declaration

  • city: string
  • line1: string
  • line2: string
  • postalCode: string
  • state: string

AlertContent

AlertContent: string | React.ReactElement

AsyncSelectValue

AsyncSelectValue: SelectOption | null

The value type for ValidatedAsyncSelect.

AsyncValidator

AsyncValidator<TValue>: (input: TValue) => CancellablePromise<ValidatorOutput>

Type parameters

  • TValue

Type declaration

    • The "contract" that all async validators must implement.

      Parameters

      • input: TValue

      Returns CancellablePromise<ValidatorOutput>

BooleanRadioInputValue

BooleanRadioInputValue: boolean | null

Confirmation

Confirmation: string | React.ReactElement

DateInputValue

DateInputValue: moment.Moment | null

This moment doesn't have to be a specific time zone. UTC is fine, for example.

DefaultItiReactContextData

DefaultItiReactContextData: Pick<ItiReactContextData, "themeColors" | "fieldLengths">

EasyFormDialogFormData

EasyFormDialogFormData: {}
deprecated

Type declaration

  • [name: string]: string | boolean

EasyFormDialogOnSubmitReturn

EasyFormDialogOnSubmitReturn<TResponseData>: { responseData: TResponseData; shouldClose?: boolean } | undefined

Type parameters

  • TResponseData

FileInputValue

FileInputValue: File | null

GetSelectStyles

GetSelectStyles: (options: GetSelectStylesOptions) => Required<StylesConfig<SelectOption, boolean, GroupBase<SelectOption>>>

Type declaration

ITIDispatch

ITIDispatch: Dispatch<ITIAction>

LinkButtonProps

LinkButtonProps: Omit<React.DetailedHTMLProps<HTMLAttributes<HTMLAnchorElement>, HTMLAnchorElement>, "href" | "onClick"> & { onClick?: any }

MultiSelectValue

MultiSelectValue: string[] | number[]

The value type for ValidatedMultiSelect.

NoOptionsMessage

NoOptionsMessage: (obj: { inputValue: string }) => string

Type declaration

    • (obj: { inputValue: string }): string
    • Parameters

      • obj: { inputValue: string }
        • inputValue: string

      Returns string

PersonNamePersonNameInputAttributes

PersonNamePersonNameInputAttributes: Omit<React.HTMLProps<HTMLInputElement>, "disabled">

PersonNamePersonNameInputAttributesMap

RadioInputValue

RadioInputValue: string | number | null

The value type for RadioInput.

SelectValue

SelectValue: string | number | null

The value type for ValidatedSelect.

SubmitButtonProps

SubmitButtonProps: SubmitButtonOwnProps & (Omit<React.ButtonHTMLAttributes<HTMLButtonElement>, "type"> | Omit<React.HTMLProps<HTMLAnchorElement>, "type">)

Tab

Tab: [string, string] | [string, string, TabOptions]

[tabId, tabName, tabOptions]

TabManagerRenderTab

TabManagerRenderTab: [string, boolean, React.ReactNode]

A tuple representing the content of a tab in TabManager.

The tuple elements represent tabName, isTabReadyForDisplay (loading indicator shown if false), and finally the actual tab content JSX.

TdLinkProps

TdLinkProps: PropsWithChildren<Omit<LinkProps, "to">>

TimeInputValue

TimeInputValue: { ampm: "am" | "pm" | undefined; hours: number | undefined; minutes: number | undefined }

The value type of the TimeInput component.

hours will always be between 1 and 12.

We don't do TimeInputValue = Moment because representing time of day with a datetime leads to DST bugs.

Type declaration

  • ampm: "am" | "pm" | undefined
  • hours: number | undefined
  • minutes: number | undefined

TimeZoneInputValue

TimeZoneInputValue: string | null

UseSimpleAutoRefreshQueryProps

UseSimpleAutoRefreshQueryProps<TQueryParams, TResult>: Pick<UseSimpleQueryProps<TQueryParams, TResult>, "queryParams" | "query" | "shouldQueryImmediately" | "onResultReceived" | "onLoadingChange" | "debounceDelay"> & AutoRefreshOptions

Type parameters

  • TQueryParams

  • TResult

UseSimpleParameterlessAutoRefreshQueryProps

UseSimpleParameterlessAutoRefreshQueryProps<TResult>: Pick<UseSimpleQueryProps<undefined, TResult>, "query" | "onResultReceived" | "onLoadingChange"> & AutoRefreshOptions

Type parameters

  • TResult

UseSimpleParameterlessQueryProps

UseSimpleParameterlessQueryProps<TResult>: Pick<UseSimpleQueryProps<undefined, TResult>, "query" | "onResultReceived" | "onLoadingChange" | "onError">

Type parameters

  • TResult

ValidatedInputOmittedHtmlProps

ValidatedInputOmittedHtmlProps: "id" | "name" | "class" | "disabled" | "value" | "onChange"

Validator

Validator<TValue>: (value: TValue) => ValidatorOutput

Type parameters

  • TValue

Type declaration

ValidatorOutput

ValidatorOutput: string | undefined | null | React.ReactNode

If the value is valid, a validator should return something falsy (undefined, null, or ''). If the value is invalid, the validator should return validation feedback which will be displayed to the user. The validation feedback can be a string or a ReactNode (e.g. a JSX element).

There are two special values of ValidatorOutput:

  • ASYNC_VALIDATION_PENDING: The value should be considered invalid because async validation is in progress.
  • ASYNC_VALIDATION_DEBOUNCE_PENDING: The value should be considered invalid because async validation has not started yet.
  • INVALID_NO_FEEDBACK: The value is invalid but no feedback should be displayed because the reason why the input is invalid is being displayed somewhere else.

Variables

ASYNC_VALIDATION_DEBOUNCE_PENDING

ASYNC_VALIDATION_DEBOUNCE_PENDING: "ASYNC_VALIDATION_DEBOUNCE_PENDING" = "ASYNC_VALIDATION_DEBOUNCE_PENDING"

ASYNC_VALIDATION_PENDING

ASYNC_VALIDATION_PENDING: "ASYNC_VALIDATION_PENDING" = "ASYNC_VALIDATION_PENDING"

AddressInput

AddressInput: MemoExoticComponent<(options: AddressInputProps) => Element> = ...

A validated address input. Supports US and Canadian addresses.

Field lengths and the default value of allowCanadian are configured via ItiReactContext.

AddressValidators

AddressValidators: { required: () => Validator<AddressInputValue> } = ...

Validators for use with AddressInput.

AdvancedPhoneNumberUtil

AdvancedPhoneNumberUtil: { lenWithCountryCode: number; template: string; visibleLen: number; formatter: any }

Type declaration

  • lenWithCountryCode: number
  • template: string
  • visibleLen: number
  • formatter:function
    • formatter(s: string): { text: string }
    • Parameters

      • s: string

      Returns { text: string }

      • text: string

AsyncSelectUtil

AsyncSelectUtil: { getNoOptionsMessage: (entityNamePlural: string) => NoOptionsMessage; getPlaceholder: (entityNamePlural: string) => string } = ...

Type declaration

  • getNoOptionsMessage: (entityNamePlural: string) => NoOptionsMessage
      • Parameters

        • entityNamePlural: string

        Returns NoOptionsMessage

        e.g. "No users matched your search" or "Begin typing to see matching users"

  • getPlaceholder: (entityNamePlural: string) => string
      • (entityNamePlural: string): string
      • Parameters

        • entityNamePlural: string

        Returns string

        e.g. "Search users..."

AsyncSelectValidators

AsyncSelectValidators: { required: () => Validator<AsyncSelectValue> } = ...

Type declaration

BooleanRadioValidators

BooleanRadioValidators: { required: () => Validator<BooleanRadioInputValue> } = ...

DateInput

DateInput: NamedExoticComponent<DateInputProps> = ...

A datetime input with a datepicker popover. See also DateInputNoPicker.

It is implemented using react-datepicker.

DateInputNoPicker

DateInputNoPicker: NamedExoticComponent<DateInputNoPickerProps> = ...

A datetime input without a datepicker popover. Its value is just a string. Good for things like date of birth. See also DateInput.

Use formatDateInputNoPickerValue to get the initial value for this input.

Use parseDateInputNoPickerValue to get a moment object from the string.

DateInputNoPickerValidators

DateInputNoPickerValidators: { required: (options: { includesTime: boolean }) => Validator<string> } = ...

Validators for use with DateInputNoPicker.

Type declaration

  • required: (options: { includesTime: boolean }) => Validator<string>
      • (options: { includesTime: boolean }): Validator<string>
      • Parameters

        • options: { includesTime: boolean }
          • includesTime: boolean

        Returns Validator<string>

DateValidators

DateValidators: { required: (options: { includesTime: boolean }) => Validator<DateInputValue> } = ...

Validators for use with DateInput.

Type declaration

FileValidators

FileValidators: { required: () => Validator<FileInputValue> } = ...

For use with FileInput.

Type declaration

FormCheck

FormCheck: NamedExoticComponent<FormCheckProps> = ...

An easy to use checkbox component.

<FormCheck
checked={myBoolean}
onChange={() => setMyBoolean(b => !b)}
label="My checkbox"
/>

inline is true by default and should be set to false if you want to display a vertical stack of checkboxes.

INVALID_NO_FEEDBACK

INVALID_NO_FEEDBACK: "INVALID_NO_FEEDBACK" = "INVALID_NO_FEEDBACK"

InternalAddressValidators

InternalAddressValidators: { allFieldLengthsValid: (fieldLengths: AddressInputFieldLengths) => Validator<AddressInputValue>; allFieldsValid: (postalCodeValidationOptions: PostalCodeValidationOptions) => Validator<AddressInputValue>; disallowPartialAddress: () => Validator<AddressInputValue> } = ...

Validators you can use to build your own custom address input.

Type declaration

ItiReactContext

ItiReactContext: Context<ItiReactContextData> = ...

A context that provides configuration values used by code within iti-react-core. You must wrap your application in with <ItiReactContext.Provider> and <ItiReactCoreContext.Provider>.

ItiReactCoreContext

ItiReactCoreContext: React.Context<ItiReactCoreContextData>

A context that provides configuration values used by code within iti-react-core. You must wrap your application in with <ItiReactCoreContext.Provider>.

MultiSelectValidators

MultiSelectValidators: { required: () => Validator<MultiSelectValue> } = ...

Type declaration

Pager

Pager: NamedExoticComponent<PagerProps> = ...

A simple pagination control that does not allow setting the number of items on a page.

These days, ConfigurablePager is generally preferred.

PersonNameInput

PersonNameInput: MemoExoticComponent<(options: PersonNameInputProps) => Element> = ...

A person name input that displays inputs for first name, middle name (optional), and last name.

If we just want first and last name, we will often just use two normal [[ValidatedInputs]] instead of PersonNameInput.

PersonNameValidators

PersonNameValidators: { required: () => Validator<PersonNameInputValue> } = ...

Validators for use with PersonNameInput.

RadioInput

RadioInput: NamedExoticComponent<RadioInputProps> = ...

Radio button input. It renders a group of radio buttons based on the options you pass in.

You can customize the style of both the container and the individual radio buttons / labels. Use the devtools element inspector to see the class names you need to target.

RadioValidators

RadioValidators: { required: () => Validator<RadioInputValue> } = ...

Type declaration

SelectValidators

SelectValidators: { required: () => Validator<SelectValue> } = ...

Type declaration

TimeInput

TimeInput: NamedExoticComponent<TimeInputProps> = ...

A time of day input with dropdowns for hours, minutes, and am/pm.

Make sure to pass individualInputsRequired=true and isClearable=false as well as TimeValidators.required() if the time is required.

It's not the most performant or user-friendly component but it has gotten the job done so far.

TimeValidators

TimeValidators: { required: () => Validator<TimeInputValue> } = ...

Validators for use with TimeInput.

Type declaration

TimeZoneValidators

TimeZoneValidators: { required: () => Validator<TimeZoneInputValue> } = ...

ValidatedAsyncSelect

ValidatedAsyncSelect: NamedExoticComponent<ValidatedAsyncSelectProps> = ...

A validated dropdown component based on react-select that loads its options via an API call.

This component is expensive to render so use React.memo when necessary.

ValidatedInput

ValidatedInput: MemoExoticComponent<(options: ValidatedInputProps) => Element> = ...

ValidatedMultiSelect

ValidatedMultiSelect: MemoExoticComponent<(options: ValidatedMultiSelectProps) => Element> = ...

A validated dropdown component based on react-select that allows selecting multiple options.

If any options have isFixed: true, you should sort the options so that fixed options come before unfixed. Sorting the options in the component would cause poor performance when there are many options and the options array is not referentially stable.

This component is expensive to render so use React.memo when necessary.

ValidatedSelect

ValidatedSelect: MemoExoticComponent<(options: ValidatedSelectProps) => Element> = ...

A validated dropdown component based on react-select.

This component is expensive to render so use React.memo when necessary.

Validators

Validators: { email: typeof email; greaterThan: typeof greaterThan; greaterThanOrEqual: typeof greaterThanOrEqual; integer: typeof integer; lessThan: typeof lessThan; lessThanOrEqual: typeof lessThanOrEqual; maxLength: typeof maxLength; minLength: typeof minLength; money: typeof money; number: typeof number; required: typeof required }

Validators for string values. Each property on this object is a function that returns a Validator<string>.

const validators = [Validators.required(), Validators.integer(), Validators.greaterThan(0)]

Type declaration

  • email: typeof email
  • greaterThan: typeof greaterThan
  • greaterThanOrEqual: typeof greaterThanOrEqual
  • integer: typeof integer
  • lessThan: typeof lessThan
  • lessThanOrEqual: typeof lessThanOrEqual
  • maxLength: typeof maxLength
  • minLength: typeof minLength
  • money: typeof money
  • number: typeof number
  • required: typeof required

canadianProvinces

canadianProvinces: StateOrProvince[] = ...

dateInputFormat

dateInputFormat: "M/D/YYYY" = 'M/D/YYYY'

The moment format string used by DateInput and DateInputNoPicker when includesTime is false.

dateTimeInputFormat

dateTimeInputFormat: string = ...

The moment format string used by DateInput and DateInputNoPicker when includesTime is true.

defaultAddressInputValue

defaultAddressInputValue: AddressInputValue = ...

defaultItiReactContextData

defaultItiReactContextData: DefaultItiReactContextData = ...

Defaults for parts of ItiReactContextData. Does not include defaults for properties where there is no reasonable default value.

defaultItiReactCoreContextData

defaultItiReactCoreContextData: DefaultItiReactCoreContextData

Defaults for parts of ItiReactCoreContextData. Does not include defaults for properties where there is no reasonable default value.

defaultPersonNameInputValue

defaultPersonNameInputValue: PersonNameInputValue = ...

defaultPostalCodeValidationOptions

defaultPostalCodeValidationOptions: PostalCodeValidationOptions = ...

defaultTimeInputValue

defaultTimeInputValue: TimeInputValue = ...

pageActions

pageActions: { setPage: PayloadActionCreator<"SET_PAGE", number>; setPageSize: PayloadActionCreator<"SET_PAGE_SIZE", number>; showAllItems: EmptyActionCreator<"SHOW_ALL_ITEMS"> } = ...
internal

Type declaration

  • setPage: PayloadActionCreator<"SET_PAGE", number>
  • setPageSize: PayloadActionCreator<"SET_PAGE_SIZE", number>
  • showAllItems: EmptyActionCreator<"SHOW_ALL_ITEMS">

pageReducer

pageReducer: Reducer<{ page: number; pageSize: number }, PayloadAction<"SET_PAGE", number> | PayloadAction<"SET_PAGE_SIZE", number> | EmptyAction<"SHOW_ALL_ITEMS">> & { handleAction: HandleActionChainApi<{ page: number; pageSize: number }, never, PayloadAction<"SET_PAGE", number> | PayloadAction<"SET_PAGE_SIZE", number> | EmptyAction<"SHOW_ALL_ITEMS">>; handlers: Record<"SET_PAGE" | "SET_PAGE_SIZE" | "SHOW_ALL_ITEMS", (state: { page: number; pageSize: number }, action: PayloadAction<"SET_PAGE", number> | PayloadAction<"SET_PAGE_SIZE", number> | EmptyAction<"SHOW_ALL_ITEMS">) => { page: number; pageSize: number }> } = ...
internal

Functions

ActionDialog

AddressDisplay

BooleanRadioInput

Breadcrumbs

ClickToCopy

ConfigurablePager

ConfirmDialog

DefaultClearButtonComponent

Dialog

  • Dialog(options: PropsWithChildren<DialogProps>): React.ReactElement
  • Wrapper around the Bootstrap dialog component.

    • DO NOT unmount the dialog except in the onClose function. This will cause the dialog to be abruptly removed without an animation.
    • Use closeRef to close the dialog from the parent component.
    • The first input element is automatically focused when the dialog opens. This can be controlled with the focusFirst and focusFirstOptions props.

    Parameters

    Returns React.ReactElement

EasyFormDialog

  • A wrapper around ActionDialog that removes a lot of the boilerplate needed for dialogs that contain a form.

    interface ExampleProps {
    onSuccess(responseData: number): Promise<void>
    onClose(): void
    }

    export function Example({
    onSuccess,
    onClose,
    }: ExampleProps): ReactElement {
    const { onChildValidChange, allFieldsValid } = useFieldValidity()
    const [showValidation, setShowValidation] = useState(false)
    const vProps = { showValidation, onValidChange: onChildValidChange }

    const [myNumber, setMyNumber] = useState('')

    async function submit() {
    await api.product.performOperation()

    return {
    responseData: parseInt(myNumber),
    }
    }

    return (
    <EasyFormDialog
    title="Enter a Number"
    submitButtonText="Submit"
    formIsValid={allFieldsValid}
    showValidation={showValidation}
    onShowValidationChange={setShowValidation}
    onSubmit={submit}
    onSuccess={onSuccess}
    onClose={onClose}
    >
    <FormGroup label="My number">
    {(id) => (
    <ValidatedInput
    id={id}
    name="myNumber"
    validators={[Validators.required(), Validators.integer()]}
    value={myNumber}
    onChange={setMyNumber}
    {...vProps}
    />
    )}
    </FormGroup>
    </EasyFormDialog>
    )
    }

    Parameters

    Returns React.ReactElement

ErrorRouteSynchronizer

  • A React component that adds a URL search param (usually error) if the error prop is non-null. If the error prop is null, the URL search param is removed.

    Usually, the error prop will come from the Redux store. This allows you to display an error page whenever an error occurs anywhere in your application.

    Test Cases

    1. When an error occurs, the error param is added to the URL and the error page is displayed.
    2. When the URL contains the error param and user refreshes the page, the error param is removed and the error page is not displayed.
    3. When the user is on the error page and clicks back, they are returned to the page they were on when the error occurred.
    4. This tests the errorKey functionality. a. Error occurs, and error page is displayed. b. User navigates to some other page. c. Another error occurs. Make sure the error page is displayed.

    Parameters

    Returns null

FileInput

FormGroup

LinkButton

MoneyInputContainer

  • MoneyInputContainer(options: { children?: ReactNode }): React.ReactElement

PhoneInput

  • A validated phone number input. It automatically adds the US/Canada country code (1) to the value. Other country codes are not currently supported.

    You don't have to pass in a validator that checks that the phone number is valid — this is done automatically. PhoneInput can be used with Validators.required().

    Parameters

    Returns React.ReactElement

SavedMessage

  • Shows a "✔ Saved" message next to your "Save changes" button to show that user that the change went through. The message fades in and out.

    const showSavedMessageRef = useRef(() => {})

    function saveChanges() {
    // call the API

    showSavedMessageRef.current()
    }

    return <div>
    ...
    <SavedMessage
    showSavedMessageRef={showSavedMessageRef}
    className="saved-message-me"
    />
    ...
    </div>

    Parameters

    Returns React.ReactElement

SubmitButton

TabContentLoading

TabLayout

TabManager

  • A high-level component for creating user interfaces with tabs.

    • It stores the current tab name as a URL search params.
    • It doesn't mount the a tab until the user actually visits that tab. (You can disable this with by setting mountAllTabs to true.)
    • It shows a loading indicator if a tab needs to load data before it can render content.

    Parameters

    Returns React.ReactElement | null

TimeZoneInput

UnitInputContainer

ValidationFeedback

alert

allReady

  • allReady<T>(readiness: T): boolean

areLocationsEquivalent

  • areLocationsEquivalent(a: Location, b: Location): boolean

cleanUpImproperlyClosedDialog

  • cleanUpImproperlyClosedDialog(): void

combineValidatorOutput

  • Takes in multiple ValidatorOutput's and returns the first invalid one, or undefined if all are valid.

    Parameters

    Returns ValidatorOutput

confirm

Const filterOption

  • filterOption(option: FilterOptionOption<unknown>, rawInput: string): boolean

focusFirstInput

  • focusFirstInput(parentElement: HTMLElement): void

formatAddressLine3

  • formatAddressLine3(partialAddress: { city: undefined | null | string; postalCode: undefined | null | string; state: undefined | null | string }): string
  • Formats the "city state zip" part of an address.

    Parameters

    • partialAddress: { city: undefined | null | string; postalCode: undefined | null | string; state: undefined | null | string }
      • city: undefined | null | string
      • postalCode: undefined | null | string
      • state: undefined | null | string

    Returns string

formatDateInputNoPickerValue

  • formatDateInputNoPickerValue(m: Moment, options: { includesTime: true; timeZone: string } | { includesTime: false }): string

formatDateTimeConfigurable

  • formatDateTimeConfigurable(mo: Moment, options: { convertToLocal: boolean; dateTimeFormat: string; onlyShowDateIfNotToday: boolean; timeFormat: string }): string
  • A configurable function for formatting a moment.

    Parameters

    • mo: Moment

      any moment object

    • options: { convertToLocal: boolean; dateTimeFormat: string; onlyShowDateIfNotToday: boolean; timeFormat: string }
      • onlyShowDateIfNotToday: when true, does not display the day if mo is today
      • convertToLocal: if mo should be converted to local time
      • dateTimeFormat: format used if date & time are displayed
      • timeFormat: format used if only time is displayed
      • convertToLocal: boolean
      • dateTimeFormat: string
      • onlyShowDateIfNotToday: boolean
      • timeFormat: string

    Returns string

formatDollars

  • formatDollars(amount: undefined | null | number): string
  • Formats a dollar amount. Supports negative values.

    Parameters

    • amount: undefined | null | number

    Returns string

formatPercent

  • formatPercent(amount: undefined | null | number, purpose: "display" | "userInput", precision?: number): string
  • Formats a number as a percent. An input value of 1 means 100%.

    Supports negative values.

    Parameters

    • amount: undefined | null | number
    • purpose: "display" | "userInput"

      'display' if this percentage will be displayed, 'userInput' if percent will be used as the default value for a text input.

    • Optional precision: number

    Returns string

formatPhoneNumber

  • formatPhoneNumber(phoneNumber: undefined | null | string): string
  • Format a phone number for display. Uses normalizePhoneNumber.

    Parameters

    • phoneNumber: undefined | null | string

    Returns string

formatPostalCode

  • formatPostalCode(postalCode: undefined | null | string): string
  • Normalizes and converts a postal code to a string. Handles 5 & 9 digit US postal codes and Canadian postal codes.

    Parameters

    • postalCode: undefined | null | string

    Returns string

getAsyncRouter

  • getAsyncRouter<TOnReadyArgs>(): React.VoidFunctionComponent<AsyncRouterProps<TOnReadyArgs>>
  • A component factory that returns an AsyncRouter. When using AsyncRouter and a link changes the route, the new page is mounted but not displayed until it has finished loading data and calls onReady. A progress bar at the top of the page (usually NProgress) indicates to the user that the new page is loading.

    It is fine if a page calls onReady multiple times.

    Example:

    export interface OnReadyArgs {
    title: string
    }

    const AsyncRouter = getAsyncRouter<OnReadyArgs>()

    export function MyAsyncRouter(): React.ReactElement {
    const onReady = useCallback(
    ({ title }: OnReadyArgs): void => {
    updateTitle(title)
    },
    []
    )

    const onInitialPageReady = useCallback((): void => {
    removeLoadingScreen()
    }, [])

    return (
    <AsyncRouter
    renderRoutes={props => <AppRoutes {...props} />}
    renderLayout={(children) => (
    <Layout>
    {children}
    </Layout>
    )}
    getLocationKey={getLocationKey}
    onNavigationStart={NProgress.start}
    onNavigationDone={NProgress.done}
    onReady={onReady}
    onInitialPageReady={onInitialPageReady}
    />
    )
    }

    function getLocationKey(location: Location): string {
    return location.pathname.toLowerCase()
    }

    getLocationKey

    • If you want to be able to change the route parameters without the page unmounting and remounting, you should implement getLocationKey, so that the page has the same location key regardless of the route params.

      Example: you want to be able to navigate from /job/0 to /job/1 without the page remounting. You should make getLocationKey return '/job' for any path that matches '/job/:page?. Use matchPath for this.

      LocationKey is NOT the same as the key property of the location object.

    • When implementing getLocationKey, if the current path does not correspond to a route in your application, you must return the current path without any modifications.

      Consider this example to see why you must return the path unmodified. Say you have a route /job/:page? and you have implemented getLocationKey to return '/job' for any path that starts with /job. The user enters /job/bogus/path/here into the URL bar. The "Page not found" page will be rendered. Then the user clicks the navbar link to the job list. The location key does not change when the location changes, so AsyncRouter does not unmount the previous page and mount the new page. But the two pages are actually different! So yeah weird stuff can happen if you implement getLocationKey like this. Always use matchPath in getLocationKey!

    Test Cases

    1. Normal navigation.
    2. Double click a link - navigation should still occur like normal.
    3. Click a link and press browser back button while page is loading.
    4. Click a link and then click a different link while page is loading.
    5. Go to the "Spam onReady" page in test-website and follow the steps.
    6. Redirect to self: click the ITI React "logo" in test-website while on /home. The logo is a link to /. When the path is /, a redirect to /home is rendered, putting you back where you started.

    Type parameters

    • TOnReadyArgs

      the arguments your pages will pass to onReady

    Returns React.VoidFunctionComponent<AsyncRouterProps<TOnReadyArgs>>

getCombinedValidatorOutput

  • Applies multiple validators to a value and returns the combined result. Thin wrapper around combineValidatorOutput.

    Type parameters

    • TValue

    Parameters

    Returns ValidatorOutput

getGuid

  • getGuid(): string
  • Returns string

getNonGroupOptions

getPage

  • getPage<T>(allItems: T[], page: number, pageSize: number): T[]
  • Returns a page of items, given the page number (which starts at 1) and the page size.

    Type parameters

    • T

    Parameters

    • allItems: T[]
    • page: number
    • pageSize: number

    Returns T[]

Const getSelectStyles

getStateOptions

  • getStateOptions(options: { includeCanadianProvinces: boolean; includeUsStates: boolean }): SelectOption[] | GroupBase<SelectOption>[]

getStates

  • getStates(options: { includeCanadianProvinces: boolean; includeUsStates: boolean }): StateOrProvince[]

getSubmitEnabled

  • getSubmitEnabled(formIsValid: boolean, showValidation: boolean): boolean
  • Returns a boolean indicating if a form's submit button should be enabled.

    Returns true if formIsValid === true or showValidation === false.

    This has the effect of disabling the submit button while async validation is in progress if validation is being shown.

    Parameters

    • formIsValid: boolean
    • showValidation: boolean

    Returns boolean

getTabFromLocation

  • getTabFromLocation(tabs: Tab[], location: Location, options?: { defaultTabName?: string; urlParamName?: string }): string

getTdLink

  • getTdLink(to: string, tdProps?: HTMLProps<HTMLTableCellElement>): React.FC<TdLinkProps>
  • Makes a table cell into a link.

    TdLink has styles that are required for it to work correctly.

    <table className="table table-hover table-td-link">
    <tbody>
    {products.map(p => {
    const Td = getTdLink('/product/detail/' + p.id)

    return (
    <tr key={p.id}>
    <Td>{p.id}</Td>
    <Td>{p.name}</Td>
    <Td>{p.stock}</Td>
    </tr>
    )
    })}
    </tbody>
    </table>

    Parameters

    • to: string
    • Optional tdProps: HTMLProps<HTMLTableCellElement>

    Returns React.FC<TdLinkProps>

getTotalPages

  • getTotalPages(itemCount: number, pageSize: number): number
  • Returns the total numbers of pages based on the number of items and the page size.

    Parameters

    • itemCount: number
    • pageSize: number

    Returns number

getValidationClass

  • getValidationClass(valid: boolean, showValidation: boolean): string

hasAncestor

  • hasAncestor(target: HTMLElement, selector: string): boolean

hasIErrorProperties

  • hasIErrorProperties<TType>(obj: unknown): obj is IError<TType>
  • Use this to test if an unknown is probably an IError.

    Type parameters

    • TType

    Parameters

    • obj: unknown

    Returns obj is IError<TType>

isCanadianPostalCode

  • isCanadianPostalCode(postalCode: undefined | null | string): boolean
  • Parameters

    • postalCode: undefined | null | string

    Returns boolean

    true if the postal code is Canadian e.g. A1A 1A1

isPostalCodeValid

isRunningAsJestTest

  • isRunningAsJestTest(): boolean
  • Used to run different code if running in a Jest test.

    Returns boolean

normalizePhoneNumber

  • normalizePhoneNumber(phoneNumber: string): string
  • Takes in a phone number in any format and converts it to an 11-digit string that starts with the US/Canada country code of 1.

    Parameters

    • phoneNumber: string

    Returns string

normalizePostalCode

  • normalizePostalCode(postalCode: undefined | null | string): string
  • Returns a postal code with the space or hyphen removed.

    Parameters

    • postalCode: undefined | null | string

    Returns string

nullToUndefined

  • nullToUndefined<T>(x: undefined | null | T): T | undefined
  • Converts T | null | undefined to T | undefined.

    Type parameters

    • T

    Parameters

    • x: undefined | null | T

    Returns T | undefined

parseDateInputNoPickerValue

  • parseDateInputNoPickerValue(value: string, options: { includesTime: true; timeZone: string } | { includesTime: false }): moment.Moment | undefined

Const phoneInputValidator

postalCodeValidator

preventNonExistentPage

  • preventNonExistentPage(options: { firstPage?: 0 | 1; page: number; pageHasItems: boolean; onPageChange: any }): void
  • Use this whenever doing server-side paging to account for items being deleted while the user has the list open. Without this function, the user could see an empty page because the number of items, and thus the total number of pages, has decreased.

    Part of usePaginationHelpers. Usually not used directly.

    Parameters

    • options: { firstPage?: 0 | 1; page: number; pageHasItems: boolean; onPageChange: any }
      • Optional firstPage?: 0 | 1
      • page: number
      • pageHasItems: boolean
      • onPageChange:function
        • onPageChange(page: number): void
        • Parameters

          • page: number

          Returns void

    Returns void

resetPageIfFiltersChanged

  • resetPageIfFiltersChanged<TQueryParams>(queryParams: TQueryParams, newQueryParams: TQueryParams, firstPage?: 0 | 1, selectFilters?: (queryParams: TQueryParams) => Partial<TQueryParams>): TQueryParams
  • Compares the filters between the current query params and the new query params and resets to the first page if any of the filters have changed.

    Part of usePaginationHelpers. Usually not used directly.

    Type parameters

    • TQueryParams: { page: number; pageSize?: number }

    Parameters

    • queryParams: TQueryParams
    • newQueryParams: TQueryParams
    • Optional firstPage: 0 | 1
    • Optional selectFilters: (queryParams: TQueryParams) => Partial<TQueryParams>

      determines which properties of the query params object are considered filters. By default, everything other than page and pageSize is considered a filter.

        • (queryParams: TQueryParams): Partial<TQueryParams>
        • Parameters

          • queryParams: TQueryParams

          Returns Partial<TQueryParams>

    Returns TQueryParams

timeInputValueFromDecimalHours

  • timeInputValueFromDecimalHours(decimalHours: undefined | number): TimeInputValue

timeInputValueToDecimalHours

  • timeInputValueToDecimalHours(value: TimeInputValue): number | undefined

toDecimalHours

  • toDecimalHours(hours: number, minutes: number): number
  • Converts hours & minutes to a decimal number of hours.

    toDecimalHours(5, 30) // -> 5.5
    

    Parameters

    • hours: number

      should be an integer

    • minutes: number

    Returns number

toHoursAndMinutes

  • toHoursAndMinutes(decimalHours: number): { hours: number; minutes: number }
  • Converts a decimal number of hours to integer hours & minutes.

    toHoursAndMinutes(5.5) // -> { hours: 5, minutes: 30 }
    

    Parameters

    • decimalHours: number

    Returns { hours: number; minutes: number }

    • hours: number
    • minutes: number

undefinedToNull

  • undefinedToNull<T>(x: undefined | null | T): T | null
  • Converts T | null | undefined to T | null.

    Type parameters

    • T

    Parameters

    • x: undefined | null | T

    Returns T | null

useCancellablePromiseCleanup

  • useCancellablePromiseCleanup(): CaptureCancellablePromise
  • Returns a capture function which "captures" CancellablePromise's and cancels them when the component unmounts. This prevents "set state after unmount" warnings.

    const capture = useCancellablePromiseCleanup()

    // Later, in an async function:
    const result = await capture(api.get('xyz'))

    Returns CaptureCancellablePromise

useControlledValue

  • Allows an input to work as either a controlled or uncontrolled component depending on which props are provided.

    Type parameters

    • TValue

    Parameters

    Returns { value: TValue; onChange: any }

    • value: TValue
    • onChange:function
      • onChange(value: TValue): void
      • Parameters

        • value: TValue

        Returns void

useDebouncedAsyncValidationPending

  • useDebouncedAsyncValidationPending(propsPending: boolean): boolean

useFieldValidity

  • Keep tracks of a FieldValidity and returns a function to update the the FieldValidty.

    You don't need to use this if there is only one validated input. In that case, a simple const [valid, setValid] = useState(false) is sufficient.

    Top-level usage (e.g. when using EasyFormDialog):

    const { onChildValidChange, allFieldsValid } = useFieldValidity()
    

    Usage with onValidChange from props:

    const { onChildValidChange } = useFieldValidity({ onValidChange })
    

    Parameters

    • Optional options: { defaultValue?: FieldValidity; onValidChange?: any }
      • Optional defaultValue?: FieldValidity
      • onValidChange?:function
        • onValidChange(valid: boolean): void
        • Parameters

          • valid: boolean

          Returns void

    Returns ReturnType<typeof useFieldValidityCore>

useFieldValidityCore

  • useFieldValidityCore(options: { defaultValue: undefined | FieldValidity; onValidChange: undefined | ((valid: boolean) => void); fieldValidityIsValid: any }): { allFieldsValid: boolean; fieldValidity: FieldValidity; onChildValidChange: any }
  • Like useFieldValidity, but lets you pass in whatever fieldValidityIsValid function you want.

    Usually you'll want to use useFieldValidity.

    Parameters

    • options: { defaultValue: undefined | FieldValidity; onValidChange: undefined | ((valid: boolean) => void); fieldValidityIsValid: any }
      • defaultValue: undefined | FieldValidity
      • onValidChange: undefined | ((valid: boolean) => void)
      • fieldValidityIsValid:function
        • Parameters

          Returns boolean

    Returns { allFieldsValid: boolean; fieldValidity: FieldValidity; onChildValidChange: any }

    • allFieldsValid: boolean
    • fieldValidity: FieldValidity
    • onChildValidChange:function
      • onChildValidChange(fieldName: string, valid: boolean): void
      • Parameters

        • fieldName: string
        • valid: boolean

        Returns void

usePaginationHelpers

  • usePaginationHelpers<TQueryParams>(options: { firstPage?: 0 | 1; items: unknown[]; pageSizeWhenItemsRetrieved: number; queryParams: TQueryParams; totalCount: number; onPageChange: any }): number
  • A hook that combines three things that need to be implemented when using pagination:

    • Resets page when filters change
    • Returns total number of pages
    • If the current page has no items and is not the first page, decrements the page (prevent non-existent pages). This situation occurs when someone deletes items while the user is viewing a paginated list.
    const totalPages = usePaginationHelpers(...)
    

    Type parameters

    • TQueryParams: { page: number; pageSize?: number }

    Parameters

    • options: { firstPage?: 0 | 1; items: unknown[]; pageSizeWhenItemsRetrieved: number; queryParams: TQueryParams; totalCount: number; onPageChange: any }

    Returns number

usePopoverClickListener

usePrevious

  • usePrevious<T>(value: T): T | undefined
  • Stores and returns the previous value of something. Useful in niche situations. Internally, it uses useRef.

    const previousLocation = usePrevious(location)
    

    Type parameters

    • T

    Parameters

    • value: T

    Returns T | undefined

useReadiness

  • useReadiness<TReadiness>(defaultValue: TReadiness, onChange: (readiness: TReadiness) => void): [(delta: Partial<TReadiness>) => void, TReadiness]
  • Used to call onReady when all of the components/queries in a page are ready.

    const [onChildReady, readiness] = useReadiness(
    {
    a: false, b: false, c: false
    },
    readiness => {
    if (allReady(readiness)) {
    onReady({ ... })
    }
    },
    )

    Type parameters

    • TReadiness

    Parameters

    • defaultValue: TReadiness
    • onChange: (readiness: TReadiness) => void
        • (readiness: TReadiness): void
        • Parameters

          • readiness: TReadiness

          Returns void

    Returns [(delta: Partial<TReadiness>) => void, TReadiness]

useReadyCore

useSimpleAutoRefreshQuery

  • deprecated

    Performs a query on mount and repeats the query according to refreshInterval.

    Example:

    const { doQuery, doQueryAsync } = useParameterlessAutoRefreshQuery<WorkDocId, WorkDocDto>({
    queryParams: workDocId,
    query: (id) => api.workDoc.get({ id }),
    shouldQueryImmediately: (prev, cur) => true,
    onResultReceived: (workDoc) => {
    setWorkDoc(workDoc)
    dispatch(setShowBackendUnreachableAlert(false))
    },
    refreshInterval: dayjs.duration(1, 'minute'),
    onConnectionError: () => dispatch(setShowBackendUnreachableAlert(true))
    })

    Type parameters

    • TQueryParams

      the parameters of the query

    • TResult

      the type returned by the query

    Parameters

    Returns UseSimpleQueryReturn

useSimpleParameterlessAutoRefreshQuery

  • deprecated

    Performs a query on mount and repeats the query according to refreshInterval. Use this when query doesn't depend on any outside variables, e.g. props.

    Example:

    const { doQuery, doQueryAsync } = useParameterlessAutoRefreshQuery<WorkDocDto>({
    query: api.workDoc.getcount,
    onResultReceived: (count) => {
    setCount(count)
    dispatch(setShowBackendUnreachableAlert(false))
    },
    refreshInterval: moment.duration(1, 'minute'),
    onConnectionError: () => dispatch(setShowBackendUnreachableAlert(true))
    })

    Type parameters

    • TResult

      the type returned by the query

    Parameters

    Returns UseSimpleQueryReturn

useSimpleParameterlessQuery

  • deprecated

    Performs a query on mount. Use this when query doesn't depend on any outside variables, e.g. props.

    Example:

    const { doQuery, doQueryAsync } = useSimpleParameterlessQuery<number>({
    query: api.workDoc.getCount,
    onResultReceived: (count) => {
    setCount(count)
    }
    })

    Type parameters

    • TResult

      the type returned by the query

    Parameters

    Returns UseSimpleQueryReturn

useSimpleQuery

  • deprecated

    Except for use by useAsyncValidator.

    Perform a query on mount and whenever queryParams change.

    • queryParams: must be referentially stable, otherwise there will be an infinite loop. useMemo is helpful here.
    • query: must be not depend on outside variables, e.g. props!!! Changing query does not cause the query to rerun.
    • shouldQueryImmediately: provide a function here that takes in the previous query params and the current query params and return false if you want debouncing to occur.
    • onError: only needs to be provided if this query has custom error-handling logic. If not provided, the onError from ItiReactCoreContext will be used.

    Example:

    const { doQuery, doQueryAsync } = useSimpleQuery<number, WorkDocDto>({
    queryParams: workDocId,
    query: (id) => api.workDoc.get({ id }),
    shouldQueryImmediately: (prev, cur) => true,
    onResultReceived: (workDoc) => {
    setWorkDoc(workDoc)
    }
    })

    Type parameters

    • TQueryParams

      the parameters of the query

    • TResult

      the type returned by the query

    Parameters

    Returns UseSimpleQueryReturn

    an object containing doQuery and doQueryAsync functions. doQueryAsync must be called within a try-catch.

useValidation

  • A hook that allows implementing validation in any input component.

    Internally, useValidation calls useMemo on validators and asyncValidator since those props won't have stable identities if defined during the render as is typical. If useValidation did not do this, every component that rendered a validated component would have to call useMemo on validators and asyncValidator (or move the definitions outside of the component) to prevent infinite useEffect loops.

    If and when your validators or asyncValidator do change, you must pass a different validationKey for useValidation to pick up the changes.

    Type parameters

    • TValue

      the type of the input's value

    Parameters

    Returns ValidatorOutput

waitForReactUpdatesFactory

  • waitForReactUpdatesFactory(act: (f: () => Promise<void>) => PromiseLike<void>): (options?: { ms?: number; updateCount?: number }) => Promise<void>
  • To be used with Jest fake timers. Lets timers and React component async updates run.

    import { act as reactAct } from '@testing-library/react'
    import { act as hooksAct } from '@testing-library/react-hooks'
    import { waitForReactUpdatesFactory } from '@interface-technologies/iti-react/src/TestHelpers'

    export const waitForReactUpdates = waitForReactUpdatesFactory(reactAct)
    export const waitForHookUpdates = waitForReactUpdatesFactory(hooksAct)

    Parameters

    • act: (f: () => Promise<void>) => PromiseLike<void>
        • (f: () => Promise<void>): PromiseLike<void>
        • Parameters

          • f: () => Promise<void>
              • (): Promise<void>
              • Returns Promise<void>

          Returns PromiseLike<void>

    Returns (options?: { ms?: number; updateCount?: number }) => Promise<void>

      • (options?: { ms?: number; updateCount?: number }): Promise<void>
      • To be used with Jest fake timers. Lets timers and React component async updates run.

        import { act as reactAct } from '@testing-library/react'
        import { act as hooksAct } from '@testing-library/react-hooks'
        import { waitForReactUpdatesFactory } from '@interface-technologies/iti-react/src/TestHelpers'

        export const waitForReactUpdates = waitForReactUpdatesFactory(reactAct)
        export const waitForHookUpdates = waitForReactUpdatesFactory(hooksAct)

        Parameters

        • Optional options: { ms?: number; updateCount?: number }
          • Optional ms?: number
          • Optional updateCount?: number

        Returns Promise<void>

Generated using TypeDoc