Search code examples
javascriptreactjstypescriptstyled-componentsnext.js

Styled-components with components in Nextjs


I am setting up a simple Nextjs boilerplate but can't seem to get the styled-components to work. In my file Header.tsx:

// Core Module Imports
import Link from "next/link";
import * as React from "react";

// Styled-Component Imports
import styled from "../theme/theme";

class Header extends React.Component {
    render() {
        return (
            <div>
                <Link href="/about">
                   <a>About Us</a>
                </Link>
            </div>
        );
    }
}

const StyledHeader = styled(Header)`
    width: 100vw;
    height: 10vh;
    background: #2a2c39;
    color: #ff0000;
    link-style: none;
`;

export default StyledHeader;

As you can see, I set up a simple Header component and then below I used styled() to define my css. In my file Index.tsx:

// Core Module Imports
import * as React from "react";

import StyledHeader from "../components/Header";

class Index extends React.Component {
    render() {
        return (
            <div>
                <StyledHeader />
                <p>Test Change</p>
                <div>Example Div</div>
            </div>
        );
    }
}

export default Index;

Obviously I am doing something wrong because it is not working and all I get it an unstyled link. Can anyone point me in the right direction?


Solution

  • For anyone that sees this and has a similar issue, check out this: https://github.com/zeit/next.js/issues/1942#issuecomment-313925454

    Fixed my issue.

    Hey guys. At version 3.0.1-beta.13+, you could set passHref to Link (as a boolean property) to expose its href to styled-components (or any other library that wraps its tag).

    const StyledLink = styled.a`
      color: red;
      background: blue;
    `
    
    export default ({ href, name }) => (
      <Link prefetch href={href} passHref>
        <StyledLink>{name}</StyledLink>
      </Link>
    )
    

    There are solutions in the GitHub issue for people using next-routes.