Search code examples
reactjsreach-router

Error while using Link in reach-router. But routing is working fine when I use anchor tag


This my App.js

import React from "react";
import ReactDOM from "react-dom";
import { Router, Link } from "@reach/router";
import Add from "./components/Add";
import Home from "./components/Home";
import Navbar from "./components/Navbar";
import "./css/styles.css";

const App = () => {
  return (
    <div>
      <Navbar />
      <Router>
        <Home path="/" />
        <Add path="/add" />
      </Router>
    </div>
  );
};

ReactDOM.render(<App />, document.getElementById("root"));

And this is my Navbar.js

import React from "react";
import Link from "@reach/router";
import "../css/navbar.css";

const Navbar = () => {
  return (
    <nav className="navbar">
      <div className="navitem">
        <a href="/">
          <h1>Beautiful Places</h1>
        </a>
      </div>
      <div className="navitem">
        {" "}
        <Link to="/add">
          <button className="btn">Add a Place</button>
        </Link>
      </div>
    </nav>
  );
};

export default Navbar;

But but i am getting an 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.

But when I use anchor tag instead of Link I am not getting any error and app is working fine. Need help in this regard

But when I code the whole Navbar component in App.js as following.

import React from "react";
import ReactDOM from "react-dom";
import { Router, Link } from "@reach/router";
import Add from "./components/Add";
import Home from "./components/Home";
import "./css/navbar.css";
import "./css/styles.css";

const App = () => {
  return (
    <div>
      <nav className="navbar">
        <div className="navitem">
          <Link to="/">
            <h1>Beautiful Places</h1>
          </Link>
        </div>
        <div className="navitem">
          {" "}
          <Link to="/add">
            <button className="btn">Add a Place</button>
          </Link>
        </div>
      </nav>
      <Router>
        <Home path="/" />
        <Add path="/add" />
      </Router>
    </div>
  );
};

ReactDOM.render(<App />, document.getElementById("root"));

It is working fine with above App.js.


Solution

  • You are missing the { } around your Link when importing it.

    import { Link } from "@reach/router"
    

    This should remove that error for you.