Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

feat: add-value-prop-to-dropwdown-cascader #45

Merged
merged 1 commit into from
Apr 26, 2024
Merged
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
35 changes: 33 additions & 2 deletions src/lib/dropdown/cascader/index.tsx
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
import React, { useState, useRef, useEffect } from "react";
import React, { useState, useRef, useEffect, useMemo } from "react";
import styled, { css } from "styled-components";
import scrollIntoView from "smooth-scroll-into-view-if-needed";
import { mobileStyle } from "../../../styles/common-style";
Expand Down Expand Up @@ -46,12 +46,14 @@ interface ICascader {
items: IItem[];
onSelect: (value: IItem["value"]) => void;
placeholder: string;
value?: string | number;
}

const Cascader: React.FC<ICascader> = ({
items,
onSelect,
placeholder,
value,
...props
}) => {
const [path, setPath] = useState<ILayer[]>([{ items }]);
Expand All @@ -67,6 +69,12 @@ const Cascader: React.FC<ICascader> = ({
}
//eslint-disable-next-line react-hooks/exhaustive-deps
}, [path]);

const label = useMemo(
() => (value ? findLabelByValue(items, value) : undefined),
[items, value]
);

return (
<div ref={containerRef} {...props}>
<DropdownButton
Expand All @@ -76,7 +84,7 @@ const Cascader: React.FC<ICascader> = ({
selected ? (
<StyledBaseItem current text={selected.label} />
) : (
<StyledBaseItem current text={placeholder} />
<StyledBaseItem current text={label ?? placeholder} />
)
}
/>
Expand Down Expand Up @@ -117,4 +125,27 @@ const Cascader: React.FC<ICascader> = ({
);
};

/**
* @param nodes the nodes
* @param targetValue the value to search, can be string or number
* @returns the label if the item is found, else returns undefined
*/
function findLabelByValue(
nodes: IItem[],
targetValue: string | number
): string | undefined {
for (const node of nodes) {
if (node.value == targetValue) {
return node.label;
}
if (node.children) {
const result = findLabelByValue(node.children, targetValue);
if (result) {
return result;
}
}
}
return undefined;
}

export default Cascader;
Loading