I still have my doubts about styled components, but lots of folks love 'em.
For technical reasons we had to have links in a navigation sometimes be a button.
My first pass, I had some code that was like
{!isButton ? ( <a {...(id && { id })} href={url}> {label} </a> ) : ( <button {...(id && { id })} }> {label} </button> )}
(the shtick with the "id"... I'm not sure if there's a better way to conditionally include an object propery as a component attribute...)
Anyway, by using "as" which overrides the underlying DOM element for a styled component, we can make the conditional a little more focused:
<VerticalNavigationItemContent {...(id && { id })} as={isButton ? 'button' : 'a'} {...(!isButton && { href: url })} > {label} </VerticalNavigationItemContent>
So as for the definition of VerticalNavigationItemContent, it doesn't matter if it's a "a" or a "button" to start, like in the definition:
export const VerticalNavigationItemContent = styled.a`
Which seems a little weird to me? Kind of shades of calling everything a div :-D But it works ok.
No comments:
Post a Comment