Reputation: 403
I can't seem to wrap my head around a logical statement in react.js...
here is my code:
<li key={item.title}>
{item.child_items
? <Link
activeClassName="active"
partiallyActive={true}
aria-haspopup="true"
to={`/${item.slug}`}>{item.title}</Link> //reference line
: <Link to={`/${item.slug}`}>{item.title}</Link>
}
</li>
This part is working. What I am trying to accomplish is that if item.title is "home" then the reference line (commented above) would have be to={
/}>{item.title}</Link>
I think i need a function here that renders {
/}
vs {
/${item.slug}}
or do I simply write in a nested if then statement?
Upvotes: 1
Views: 100
Reputation: 187184
A ternary in the prop value should give you what you need:
<li key={item.title}>
{item.child_items
? <Link
activeClassName="active"
partiallyActive={true}
aria-haspopup="true"
to={item.title === 'home' ? '/' : `/${item.slug}`}
>
{item.title}
</Link>
: <Link to={`/${item.slug}`}>{item.title}</Link>
}
</li>
However, when logic gets complicated, it's a good indication you should move something to it's own component where it's easier to write as much code as you cleanly need to to make something work.
function NavLink({item}) {
const toHref = item.title === 'home' ? '/' : `/${item.slug}`
if (item.child_items) {
// Link with children
return <li>
<Link
activeClassName="active"
partiallyActive={true}
aria-haspopup="true"
to={toHref}
>
{item.title}
</Link>
<li>
} else {
// Link with no children
return <li><Link to={toHref}>{item.title}</Link></li>
}
}
Now you can just:
<NavLink item={item} key={item.title} />
And you know it's going to do the right thing.
Upvotes: 1