Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

styled components, with gatsby-link anchor tag css coloring

I am trying to style a <Link/> component from gatsby-link package using styled-components package Normally I just create a const give it a Name set it equal to styled.a for example and write my css. However when I create a const for <Link/> I get a Duplicate declaration "Link" error. How do I style a <Link> component with styled-components.

Here is my code Below

import React from 'react';
import Link from 'gatsby-link';
import styled from "styled-components";

const Header = styled.div`
  margin: 3rem auto;
  max-width: 600px;
  background:red;
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
`;

const Title = styled.h1`
  color: aqua;
`;

const Link = styled.a`
  color: aqua;
`;


export default () => (
  <Header>
        <Title>
          <Link to="/">
            Gatsby
          </Link>
        </Title>
  </Header>
);
like image 683
Anders Kitson Avatar asked Apr 03 '18 20:04

Anders Kitson


Video Answer


2 Answers

You should be able to do something like:

import { Link } from 'gatsby';

const StyledLink = styled(props => <Link {...props} />)`
  color: aqua;
`;

// ...

<StyledLink to="/">
  Gatsby
</StyledLink>

Outdated version (gatsby v1, styled-components v3):

import Link from 'gatsby-link';

const StyledLink = styled(Link)`
  color: aqua;
`;

// ...

<StyledLink to="/">
  Gatsby
</StyledLink>
like image 128
Fabian Schultz Avatar answered Sep 28 '22 04:09

Fabian Schultz


Rename the Link import.

import { Link as GatsbyLink } from "gatsby";

If you name your component Link you might encounter naming collisions because that name is so ubiquitous among different frameworks. The error you describe points out that you have more than one component with the same name.

Name your components explicitly (adapted from @Fabian Schultz's answer):

import { Link as GatsbyLink } from "gatsby";

const StyledLink = styled(GatsbyLink)`
  color: aqua;
`;

// ...

<StyledLink to="/">
  Gatsby
</StyledLink>
like image 35
EliteRaceElephant Avatar answered Sep 28 '22 04:09

EliteRaceElephant