Next.js: Link as a StyledComponent

Created on 16 Jan 2017  路  8Comments  路  Source: vercel/next.js

The way Link is implemented right now, it's impossible to compose styles using styled-components without generating <a><a></a></a>.

#241 would solve. Any updates on turning Link a behavior decorator only?

Most helpful comment

Oh, I see. That's because the styled component is not an anchor. We are going to deprecate this behavior but I don't see a fix for this in the meanwhile

All 8 comments

@edygar you mean <Link href="/"><a>content</a></Link> right?

Deprecation message has just been added in https://github.com/zeit/next.js/pull/797 馃憤
We're only going to support the explicit given example: <Link href="/"><a>content</a></Link>

Does this solve your question?

@timneutkens in this case the a don't get the styles.

import Link from 'next/prefetch'
import styled from 'styled-components'

const MenuItem = styled.li`
  margin: 0 10px;
  list-style: none;
`;

const MenuLink = styled(Link)`
  font-weight: 700;
  line-height: 2.88;
`

export default () => (
  <MenuItem>
    <MenuLink href='/signin'>
      <a>Sign In</a>
    </MenuLink>
  <MenuItem>
)

Result:

<li class="cjJDVk" data-reactid="8">
  <a href="/signin" data-reactid="9">Sign In</a>
</li>

@jlcarvalho Yes, you should style the <a>:

import Link from 'next/prefetch'
import styled from 'styled-components'

const MenuLink = styled.a`
  font-weight: 700;
  line-height: 2.88;
`

export default () => (
  <Link href='/signin'>
    <MenuLink>Sign In</MenuLink>
  </Link>
)

@impronunciable I tried, but the output was:

<li class="ePmGlD">
  <a href="/signin">
    <a class="jbHZic">Sign In</a>
  </a>
</li>

Oh, I see. That's because the styled component is not an anchor. We are going to deprecate this behavior but I don't see a fix for this in the meanwhile

Exactly as @jlcarvalho said.

@impronunciable, why does it matters for Link the Element.type of its first child? I think it could only provide the click behavior. Currently it's only discouraging composability.

I tried this and it seems to be working fine?

import Link from 'next/link';
import styled from 'styled-components';

const StyledLink = styled.a`
  color: red;
  background: blue;
`;

export default ({ children }) => (  
  <Link>
    <StyledLink>{ children }</StyledLink>
  </Link>
);
Was this page helpful?
0 / 5 - 0 ratings

Related issues

wagerfield picture wagerfield  路  3Comments

knipferrc picture knipferrc  路  3Comments

flybayer picture flybayer  路  3Comments

swrdfish picture swrdfish  路  3Comments

rauchg picture rauchg  路  3Comments