Gatsby.js problem with <Link>, no matter what I try

Viewed 1225

I've a serious issue with the built-in <Link> component in Gatsby.js. I'm building a huge web project and everything was fine until I've tried to use <Link> instead of the standard <a> tag. I was frustrated to the point that I created a brand new, a blank project to test <Link> on a completely fresh project. Below you'll find the code. I'm trying to get from the index page to the contact page:

Index Page:

import React from "react"
import {Link} from "react"


const IndexPage = () => {
  return (
    <div>
      <p>Link Test</p>
      <a href="/contact/">Anchor to Contact</a>
      <Link to="/contact/">Link to Contact</Link>
 
    </div>
    )
  }
  export default IndexPage

Contact page:

import React from "react"

const Contact = () => {
    return (
        <div>
            <p>Contact page</p>
        </div>
    )
}

export default Contact;

When I use <a> tag everything is working smoothly but immediately after I'm trying to add <Link> in code I'm getting the same stupid error. It's only showing in browser not in the terminal of visual studio.

This is the error:

Error: Element type is invalid: expected a string (for built-in components) or a class/function (for composite components) but got: undefined. You likely forgot to export your component from the file it's defined in, or you might have mixed up default and named imports.

Check the render method of `IndexPage`.
▶ 21 stack frames were collapsed.
(anonymous function)
/Users/piotr/Documents/Websites/LinkTest/LinkTest/.cache/app.js:133
  130 | const preferDefault = m => (m && m.default) || m
  131 | const Root = preferDefault(require(`./root`))
  132 | domReady(() => {
> 133 |   renderer(<Root />, rootElement, () => {
  134 |     apiRunner(`onInitialClientRender`)
  135 |   })
  136 | })

Please help because I've no idea what I should try next and I'm stuck on that bug for two days. Maybe I should update gatsby, node.js, and react on my computer? It's worth trying? :)

1 Answers

You need to import Link from Gatsby, not from React:

import { Link } from "gatsby"

Gatsby routing extends from @reach/router (from React) but it adds useful enhancements specific to Gatsby, so it should be imported as a Gatsby dependency. All props are passed through to @reach/router’s Link component.

Keep in mind that, using a built-in anchor tag will refresh the whole page and the whole components (header, footer, etc), it won't be caught by the @reach/router.

While using Link component, it will only refresh the needed components, adding a more smooth behavior.

Related