I´ve got this code snippet:
JavaScript
x
26
26
1
export const MessageWindow: FunctionComponent<MessageWindowProps> = ({ children, buttonsType }) => {
2
3
return (
4
<div className={classNames()}>
5
<div className={messageWindowContent}>
6
{children}
7
</div>
8
<div className={messageWindowButtons}>
9
{buttonsType === "yesno" ?
10
<>
11
<TextButton color={TextColor.colorPrimary} onClick={function foo() { }} text="No" title="No" />
12
<TextButton color={TextColor.colorPrimary} onClick={function foo() { }} text="Yes" title="Yes" />
13
</> : buttonsType === "saveclose" ?
14
<>
15
<TextButton color={TextColor.colorPrimary} onClick={function foo() { }} text="Close" title="Close" />
16
<TextButton color={TextColor.colorPrimary} onClick={function foo() { }} text="Save" title="Save" />
17
</> : buttonsType === "close" ?
18
<>
19
<TextButton color={TextColor.colorPrimary} onClick={function foo() { }} text="Close" title="Close" />
20
</> : null
21
}
22
</div>
23
</div>
24
);
25
}
26
where “buttonsType” is those enums:
JavaScript
1
6
1
export enum ButtonsType {
2
yesno = "yesno",
3
saveclose = "saveclose",
4
close = "close"
5
}
6
I´d like to know some better way, to simplify the conditional statement. Or is it possible to have it like this?
Thank you.
Advertisement
Answer
I think Ray Hatfield’s answer is the cleanest solution and avoids repetitive JSX, but I’ll add a switch example as an option. Ternary generally seems like a poor option for this case.
JavaScript
1
36
36
1
let buttons;
2
switch (buttonsType) {
3
case 'yesno':
4
buttons =
5
<>
6
<TextButton color={TextColor.colorPrimary} onClick={function foo() { }} text="No" title="No" />
7
<TextButton color={TextColor.colorPrimary} onClick={function foo() { }} text="Yes" title="Yes" />
8
</>;
9
break;
10
case 'saveclose':
11
buttons =
12
<>
13
<TextButton color={TextColor.colorPrimary} onClick={function foo() { }} text="Close" title="Close" />
14
<TextButton color={TextColor.colorPrimary} onClick={function foo() { }} text="Save" title="Save" />
15
</>;
16
break;
17
case 'close':
18
buttons =
19
<TextButton color={TextColor.colorPrimary} onClick={function foo() { }} text="Close" title="Close" />;
20
break;
21
default:
22
buttons = null;
23
}
24
25
return (
26
<div className={classNames()}>
27
<div className={messageWindowContent}>
28
{children}
29
</div>
30
<div className={messageWindowButtons}>
31
{buttons}
32
</div>
33
</div>
34
);
35
36