Skip to content

Commit

Permalink
frontend: Add noDefault flag to Select component (#2958)
Browse files Browse the repository at this point in the history
Scope: Adding a noDefault flag to the Select component to avoid
triggering the onChange method on component did update for when we don't
want the first option in the list to be set as default.
  • Loading branch information
lucechal14 committed Mar 21, 2024
1 parent 4526c81 commit daefdfb
Show file tree
Hide file tree
Showing 2 changed files with 14 additions and 1 deletion.
4 changes: 3 additions & 1 deletion frontend/packages/core/src/Input/select.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -251,6 +251,7 @@ export interface SelectProps extends Pick<MuiSelectProps, "disabled" | "error" |
name: string;
options: SelectOption[];
onChange?: (value: string) => void;
noDefault?: boolean;
}

const Select = ({
Expand All @@ -263,6 +264,7 @@ const Select = ({
options,
onChange,
value,
noDefault,
}: SelectProps) => {
// Flattens all options and sub grouped options for easier retrieval
const flatOptions: BaseSelectOptions[] = flattenBaseSelectOptions(options);
Expand All @@ -276,7 +278,7 @@ const Select = ({
);

React.useEffect(() => {
if (flatOptions.length !== 0) {
if (flatOptions.length !== 0 && !noDefault) {
onChange && onChange(flatOptions[selectedIdx]?.value || flatOptions[selectedIdx].label);
}
}, []);
Expand Down
11 changes: 11 additions & 0 deletions frontend/packages/core/src/Input/tests/select.test.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -17,6 +17,17 @@ test("select has lower bound", () => {
expect(container.querySelector("#foobar-select")).toHaveTextContent("foo");
});

test("select doesn't have default value when rendered", () => {
const { container } = render(
<ThemeProvider>
<Select name="foobar" value="" options={[{ label: "foo" }, { label: "bar" }]} noDefault />
</ThemeProvider>
);

expect(container.querySelector("#foobar-select")).toBeInTheDocument();
expect(container.querySelector("#foobar-select")).not.toHaveTextContent("foo");
});

test("select has upper bound", () => {
const { container } = render(
<ThemeProvider>
Expand Down

0 comments on commit daefdfb

Please sign in to comment.