I´ve got this code snippet:
export const MessageWindow: FunctionComponent<MessageWindowProps> = ({ children, buttonsType }) => { return ( <div className={classNames()}> <div className={messageWindowContent}> {children} </div> <div className={messageWindowButtons}> {buttonsType === "yesno" ? <> <TextButton color={TextColor.colorPrimary} onClick={function foo() { }} text="No" title="No" /> <TextButton color={TextColor.colorPrimary} onClick={function foo() { }} text="Yes" title="Yes" /> </> : buttonsType === "saveclose" ? <> <TextButton color={TextColor.colorPrimary} onClick={function foo() { }} text="Close" title="Close" /> <TextButton color={TextColor.colorPrimary} onClick={function foo() { }} text="Save" title="Save" /> </> : buttonsType === "close" ? <> <TextButton color={TextColor.colorPrimary} onClick={function foo() { }} text="Close" title="Close" /> </> : null } </div> </div> ); }
where “buttonsType” is those enums:
export enum ButtonsType { yesno = "yesno", saveclose = "saveclose", close = "close" }
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.
let buttons; switch (buttonsType) { case 'yesno': buttons = <> <TextButton color={TextColor.colorPrimary} onClick={function foo() { }} text="No" title="No" /> <TextButton color={TextColor.colorPrimary} onClick={function foo() { }} text="Yes" title="Yes" /> </>; break; case 'saveclose': buttons = <> <TextButton color={TextColor.colorPrimary} onClick={function foo() { }} text="Close" title="Close" /> <TextButton color={TextColor.colorPrimary} onClick={function foo() { }} text="Save" title="Save" /> </>; break; case 'close': buttons = <TextButton color={TextColor.colorPrimary} onClick={function foo() { }} text="Close" title="Close" />; break; default: buttons = null; } return ( <div className={classNames()}> <div className={messageWindowContent}> {children} </div> <div className={messageWindowButtons}> {buttons} </div> </div> );