mirror of
https://github.com/bigcapitalhq/bigcapital.git
synced 2026-02-16 12:50:38 +00:00
90 lines
2.1 KiB
JavaScript
90 lines
2.1 KiB
JavaScript
import React, { useState, useMemo, useEffect } from 'react';
|
|
import { Button, MenuItem } from '@blueprintjs/core';
|
|
import { Select } from '@blueprintjs/select';
|
|
import { FormattedMessage as T } from 'react-intl';
|
|
import classNames from 'classnames';
|
|
import { CLASSES } from 'common/classes';
|
|
|
|
export default function ListSelect({
|
|
buttonProps,
|
|
defaultText,
|
|
noResultsText = <T id="no_results" />,
|
|
isLoading = false,
|
|
textProp,
|
|
labelProp,
|
|
|
|
selectedItem,
|
|
selectedItemProp = 'id',
|
|
|
|
initialSelectedItem,
|
|
onItemSelect,
|
|
disabled = false,
|
|
...selectProps
|
|
}) {
|
|
const selectedItemObj = useMemo(
|
|
() => selectProps.items.find((i) => i[selectedItemProp] === selectedItem),
|
|
[selectProps.items, selectedItemProp, selectedItem],
|
|
);
|
|
|
|
const selectedInitialItem = useMemo(
|
|
() =>
|
|
selectProps.items.find(
|
|
(i) => i[selectedItemProp] === initialSelectedItem,
|
|
),
|
|
[initialSelectedItem],
|
|
);
|
|
|
|
const [currentItem, setCurrentItem] = useState(
|
|
(initialSelectedItem && selectedInitialItem) || null,
|
|
);
|
|
|
|
useEffect(() => {
|
|
if (selectedItemObj) {
|
|
setCurrentItem(selectedItemObj);
|
|
}
|
|
}, [selectedItemObj, setCurrentItem]);
|
|
|
|
const noResults = isLoading ? (
|
|
'loading'
|
|
) : (
|
|
<MenuItem disabled={true} text={noResultsText} />
|
|
);
|
|
|
|
const itemRenderer = (item, { handleClick, modifiers, query }) => {
|
|
return (
|
|
<MenuItem
|
|
text={item[textProp]}
|
|
key={item[selectedItemProp]}
|
|
label={item[labelProp]}
|
|
onClick={handleClick}
|
|
/>
|
|
);
|
|
};
|
|
|
|
const handleItemSelect = (_item) => {
|
|
setCurrentItem(_item);
|
|
onItemSelect && onItemSelect(_item);
|
|
};
|
|
|
|
return (
|
|
<Select
|
|
itemRenderer={itemRenderer}
|
|
onItemSelect={handleItemSelect}
|
|
{...selectProps}
|
|
noResults={noResults}
|
|
disabled={disabled}
|
|
className={classNames(
|
|
CLASSES.FORM_GROUP_LIST_SELECT,
|
|
selectProps.className,
|
|
)}
|
|
>
|
|
<Button
|
|
text={currentItem ? currentItem[textProp] : defaultText}
|
|
loading={isLoading}
|
|
disabled={disabled}
|
|
{...buttonProps}
|
|
/>
|
|
</Select>
|
|
);
|
|
}
|