Skip to content

styled-components "as" prop collides with next/link #11505

@mattcarlotta

Description

@mattcarlotta

Bug report

Describe the bug

When wrapping a next Link with a styled-component, the as prop of styled-components collides with the Link's as prop, which causes styled-components to throw an Invalid tag: /path/to/dynamic/route error.

To Reproduce

  1. Wrap a styled-component around a next Link:
import React from "react";
import Link from "next/link";
import styled from "styled-components";

const StyledLink = ({ as, className, children, href }) => (
  <Link href={href} as={as} passHref>
    <a className={className}>
      {children}
    </a>
  </Link>
);

export default styled(StyledLink)`
   color: #0075e0;
   white-space: nowrap;
   text-decoration: none;
   transition: all 0.2s ease-in-out;

  &:hover {
    color: #40a9ff;
  }

  &:focus {
    color: #40a9ff;
    outline: none;
    border: 0;
  }
`;

2.) Import the styled link and pass it an as prop.

import StyledLink from "./path/to/StyledLink";

export default () => 
  <StyledLink 
    href="/post/[pid]" 
    as="/post/abc"
  >
     First Post
</StyledLink>;

Expected behavior

Not to crash.

Screenshots

sWRUed6.png

Additional context & recommendations

For the unaware, this can be confusing as to why Next crashes. Although the workaround is to simply pass the StyledLink a different named prop, other than the as prop, I'd still highly recommend including a note in the styled-components example about this potential prop naming collision.

Metadata

Metadata

Assignees

No one assigned

    Labels

    good first issueEasy to fix issues, good for newcomers

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions