Search code examples
cssnext.jshyperlinkstyled-componentsnext-link

How to add CSS or styled-components to Link tag in Next.js?


Cannot add styles in any way to next.js <Link> tag.

code:

import Link from "next/link";
import styles from "../Components.module.css";

export default function SubjectBTN({ lable, path }) {
  return (
    <Link href={path} className={styles.SubjectBTN}>
        <div>{lable}</div>
    </Link>
  );
}

Solution

  • The solution was simple, wrap all the components inside the <Link> tag with an <a> tag, plus add a passHref to the Link tag since it passes the href from the Link tag to the a tag otherwise, if you didn't add a passHref, sometimes it will show a <div> wrapping the component instead of an tag and this will result in poor SEO. The code should look as following:

    import Link from "next/link";
    import styles from "../Components.module.css";
    
    export default function SubjectBTN({ lable, path }) {
      return (
        <Link href={path} passHref>
          <a className={styles.SubjectBTN}>
            <div>{lable}</div>
          </a>
        </Link>
      );
    }
    

    more information can be found here.