Skip to content

Commit 5f34566

Browse files
authored
(fix) Compute content switcher selectedIndex from visible answers (#699)
selectedIndex was computed from the unfiltered answers array but the rendered Switch children were filtered to exclude hidden answers. When hidden answers preceded the selected answer, the index would be too high, causing Carbon to highlight the wrong option. Compute both the index and the rendered list from the same filtered visibleAnswers array.
1 parent 584f7fd commit 5f34566

File tree

1 file changed

+15
-12
lines changed

1 file changed

+15
-12
lines changed

src/components/inputs/content-switcher/content-switcher.component.tsx

Lines changed: 15 additions & 12 deletions
Original file line numberDiff line numberDiff line change
@@ -21,9 +21,14 @@ const ContentSwitcher: React.FC<FormFieldInputProps> = ({ field, value, errors,
2121
[setFieldValue],
2222
);
2323

24+
const visibleAnswers = useMemo(
25+
() => field.questionOptions.answers.filter((answer) => !answer.isHidden),
26+
[field.questionOptions.answers],
27+
);
28+
2429
const selectedIndex = useMemo(
25-
() => field.questionOptions.answers.findIndex((option) => option.concept == value),
26-
[value, field.questionOptions.answers],
30+
() => visibleAnswers.findIndex((option) => option.concept == value),
31+
[value, visibleAnswers],
2732
);
2833

2934
const isInline = useMemo(() => {
@@ -59,16 +64,14 @@ const ContentSwitcher: React.FC<FormFieldInputProps> = ({ field, value, errors,
5964
selectedIndex={selectedIndex}
6065
className={styles.selectedOption}
6166
size="md">
62-
{field.questionOptions.answers
63-
.filter((answer) => !answer.isHidden)
64-
.map((option, index) => (
65-
<Switch
66-
name={option.concept || option.value}
67-
text={t(option.label)}
68-
key={index}
69-
disabled={field.isDisabled}
70-
/>
71-
))}
67+
{visibleAnswers.map((option, index) => (
68+
<Switch
69+
name={option.concept || option.value}
70+
text={t(option.label)}
71+
key={index}
72+
disabled={field.isDisabled}
73+
/>
74+
))}
7275
</CdsContentSwitcher>
7376
</FormGroup>
7477
)

0 commit comments

Comments
 (0)