ReactSelect: Add maxDisplayDepth prop to determine max level of indention

This commit is contained in:
Gustav Hansen 2022-04-06 19:05:22 +02:00
parent 4d872656d2
commit d8e6039c79

View File

@ -24,7 +24,7 @@ const hasParent = option => !option.parent;
const hasParentOrMatchesValue = (option, value) => const hasParentOrMatchesValue = (option, value) =>
option.value === value || option.parent === value; option.value === value || option.parent === value;
const SelectTree = ({ options: defaultOptions, ...props }) => { const SelectTree = ({ options: defaultOptions, maxDisplayDepth, ...props }) => {
const flatDefaultOptions = useMemo(() => flattenTree(defaultOptions), [defaultOptions]); const flatDefaultOptions = useMemo(() => flattenTree(defaultOptions), [defaultOptions]);
const toplevelDefaultOptions = useMemo(() => flatDefaultOptions.filter(hasParent), [ const toplevelDefaultOptions = useMemo(() => flatDefaultOptions.filter(hasParent), [
flatDefaultOptions, flatDefaultOptions,
@ -60,13 +60,14 @@ const SelectTree = ({ options: defaultOptions, ...props }) => {
const CustomOption = ({ children, data, ...props }) => { const CustomOption = ({ children, data, ...props }) => {
const hasChildren = data?.children?.length > 0; const hasChildren = data?.children?.length > 0;
const { depth, value } = data; const { depth, value } = data;
const normalizedDepth = Math.min(depth, maxDisplayDepth);
return ( return (
<> <>
<components.Option {...props}> <components.Option {...props}>
<Flex alignItems="start"> <Flex alignItems="start">
<Typography textColor="neutral800"> <Typography textColor="neutral800">
<span style={{ paddingLeft: `${depth * 10}px` }}>{children}</span> <span style={{ paddingLeft: `${normalizedDepth * 10}px` }}>{children}</span>
</Typography> </Typography>
{hasChildren && ( {hasChildren && (
@ -87,7 +88,12 @@ const SelectTree = ({ options: defaultOptions, ...props }) => {
return <Select components={{ Option: CustomOption }} options={options} {...props} />; return <Select components={{ Option: CustomOption }} options={options} {...props} />;
}; };
SelectTree.defaultProps = {
maxDisplayDepth: 5,
};
SelectTree.propTypes = { SelectTree.propTypes = {
maxDisplayDepth: PropTypes.number,
options: PropTypes.array.isRequired, options: PropTypes.array.isRequired,
}; };