Reputation: 35
I have a prop isStatic
passed to a component. When isStatic===false
, I have JSX setup to prevent my component from rendering two subcomponents. Ex:
return (
<div className={classes}>
{!isStatic && <MenuOne className={menuTriggerClass} appNavItems {appNavItems} mergedNavbarOrder={mergedNavbarOrder} /> }
<NavbarTitle unconfirmedCount={unconfirmedCount} />
{!isStatic && <MenuTwo className={menuTriggerClass} />}
</div>)
NavBarTitle
needs to render between MenuOne
and MenuTwo
. However, I don't like how this looks like two checks for isStatic
. Would it make sense to use a ternary operator in this case and separate this out?
Upvotes: 0
Views: 43
Reputation: 7498
You might consider doing as the following:
return (
<div className={classes}>
{this.renderMenuItem(isStatic)}
<NavbarTitle unconfirmedCount={unconfirmedCount} />
</div>)
renderMenuItem = (isStatic) => {
isStatic? return (<MenuTwo className={menuTriggerClass}):
return ( <MenuOne className={menuTriggerClass} appNavItems {appNavItems} mergedNavbarOrder={mergedNavbarOrder} )
}
Upvotes: 0
Reputation: 110
I think that no matter what, your code won't be 100% DRY, since the Navbar needs to be rendered between the two no matter what. You would either check isStatic twice, or write two outcomes for the ternary, both returning the Navbar component like so:
return (
<div className={classes}>
{!isStatic
? (
<MenuOne className={menuTriggerClass} appNavItems {appNavItems} mergedNavbarOrder={mergedNavbarOrder} />
<NavbarTitle unconfirmedCount={unconfirmedCount} />
<MenuTwo className={menuTriggerClass} />}
)
: <NavbarTitle unconfirmedCount={unconfirmedCount} />}
</div>
Alternatively, you could create a helper function to return the jsx you want when isStatic returns true. This would then make your ternary in the return statement much more readable:
const whenStatic = () => {
return (
<MenuOne className={menuTriggerClass} appNavItems {appNavItems} mergedNavbarOrder={mergedNavbarOrder} />
<NavbarTitle unconfirmedCount={unconfirmedCount} />
<MenuTwo className={menuTriggerClass} />}
)
}
return (
<div className={classes}>
{!isStatic
? whenStatic()
: <NavbarTitle unconfirmedCount={unconfirmedCount} />}
</div>
Upvotes: 1