Ujwal Gaonkar
Ujwal Gaonkar

Reputation: 59

Uncaught TypeError: Cannot read properties of undefined (reading 'pathname') and The above error occurred in the <Link> component:

I am using react-router-dom v6 but I am following an old tutorial. I am getting above mentioned error and I tried many ways but still getting same error.

This is the file which generating error:

import React from "react";
import "./sidebar.css";
import logo from "../../images/logo.png";
import { Link } from "react-router-dom";
import { TreeView, TreeItem } from "@material-ui/lab";
import ExpandMoreIcon from "@material-ui/icons/ExpandMore";
import PostAddIcon from "@material-ui/icons/PostAdd";
import AddIcon from "@material-ui/icons/Add";
import ImportExportIcon from "@material-ui/icons/ImportExport";

const Sidebar = () => {
  return (
     <div className="sidebar">
      <Link to="/">
        <img src={logo} alt="Ecommerce" />
      </Link>
      <Link to="/admin/dashboard">
        <p>
        Dashboard
        </p>
      </Link>
      <Link>
        <TreeView
          defaultCollapseIcon={<ExpandMoreIcon />}
          defaultExpandIcon={<ImportExportIcon />}
        >
          <TreeItem nodeId="1" label="Products">
            <Link to="/admin/products">
              <TreeItem nodeId="2" label="All" icon={<PostAddIcon />} />
            </Link>

            <Link to="/admin/product">
              <TreeItem nodeId="3" label="Create" icon={<AddIcon />} />
            </Link>
          </TreeItem>
        </TreeView>
      </Link>
    </div>
  );
};

export default Sidebar;

Upvotes: 1

Views: 1150

Answers (1)

Drew Reese
Drew Reese

Reputation: 202676

You've a Link component without a to prop wrapping the TreeView component. to is a required prop.

Link

interface LinkProps
  extends Omit<
    React.AnchorHTMLAttributes<HTMLAnchorElement>,
    "href"
  > {
  replace?: boolean;
  state?: any;
  to: To; // <-- non-optional
  reloadDocument?: boolean;
}

I don't think a link makes sense here so I suggest just removing it.

Example:

const Sidebar = () => {
  return (
    <div className="sidebar">
      <Link to="/">
        <img src={logo} alt="Ecommerce" />
      </Link>
      <Link to="/admin/dashboard">
        <p>Dashboard</p>
      </Link>
      <TreeView
        defaultCollapseIcon={<ExpandMoreIcon />}
        defaultExpandIcon={<ImportExportIcon />}
      >
        <TreeItem nodeId="1" label="Products">
          <Link to="/admin/products">
            <TreeItem nodeId="2" label="All" icon={<PostAddIcon />} />
          </Link>

          <Link to="/admin/product">
            <TreeItem nodeId="3" label="Create" icon={<AddIcon />} />
          </Link>
        </TreeItem>
      </TreeView>
    </div>
  );
};

Edit uncaught-typeerror-cannot-read-properties-of-undefined-reading-pathname-and

If you did actually mean for a Link to wrap all of that sub-menu then it needs the required to prop.

Upvotes: 1

Related Questions