Skip to content

Commit b39e7f8

Browse files
Elena RashkovanLena Rashkovan
andauthored
fix(combo-box): fix clearing the state in the controlled variant (#505)
Co-authored-by: Lena Rashkovan <[email protected]>
1 parent 09f0132 commit b39e7f8

File tree

2 files changed

+55
-3
lines changed

2 files changed

+55
-3
lines changed

src/components/experimental/ComboBox/ComboBox.tsx

Lines changed: 6 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -57,15 +57,18 @@ const ComboBoxInput = React.forwardRef<HTMLDivElement, ComboBoxFieldProps>(
5757
<FakeInput $isVisuallyFocused={state?.isOpen} ref={forwardedRef} onClick={() => inputRef.current?.focus()}>
5858
{leadingIcon}
5959
<InnerWrapper>
60-
<Label $flying={Boolean(placeholder || state?.inputValue.length > 0)}>{label}</Label>
60+
<Label $flying={Boolean(placeholder || state?.inputValue?.length > 0)}>{label}</Label>
6161
<Input placeholder={placeholder} ref={inputRef} />
6262
</InnerWrapper>
63-
{state?.inputValue.length > 0 ? (
63+
{state?.inputValue?.length > 0 ? (
6464
<Button
6565
// Don't inherit default Button behavior from ComboBox.
6666
slot={null}
6767
aria-label={ariaStrings.clearFieldButton}
68-
onPress={() => state?.setSelectedKey(null)}
68+
onPress={() => {
69+
state?.setSelectedKey(null);
70+
state?.setInputValue('');
71+
}}
6972
>
7073
<XCrossCircleIcon />
7174
</Button>

src/components/experimental/ComboBox/docs/ComboBox.stories.tsx

Lines changed: 49 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -104,3 +104,52 @@ export const AsyncValues: StoryObj<typeof ComboBox<Character>> = {
104104
);
105105
}
106106
};
107+
108+
export const FullyControlled: Story = {
109+
render: () => {
110+
const [items, setItems] = React.useState<Character[]>([]);
111+
const [filterText, setFilterText] = React.useState('');
112+
const [key, setKey] = React.useState<string | null>(null);
113+
114+
React.useEffect(() => {
115+
let ignore = false;
116+
117+
async function startFetching() {
118+
const res = await fetch(`https://swapi.py4e.com/api/people/?search=${filterText}`);
119+
const json = await res.json();
120+
121+
if (!ignore) {
122+
setItems(json.results);
123+
}
124+
}
125+
126+
// eslint-disable-next-line no-void
127+
void startFetching();
128+
129+
return () => {
130+
ignore = true;
131+
};
132+
}, [filterText]);
133+
134+
return (
135+
<ComboBox
136+
label="Star Wars Character"
137+
items={items}
138+
inputValue={filterText}
139+
selectedKey={key}
140+
onSelectionChange={newKey => {
141+
setFilterText(newKey as string);
142+
setKey(newKey as string);
143+
}}
144+
onInputChange={input => {
145+
setFilterText(input);
146+
if (input === '') {
147+
setKey(null);
148+
}
149+
}}
150+
>
151+
{item => <ListBoxItem id={item.name}>{item.name}</ListBoxItem>}
152+
</ComboBox>
153+
);
154+
}
155+
};

0 commit comments

Comments
 (0)