Skip to content
Advertisement

I can’t import Link attribute from react-router-dom

I tried to import Link from react-router-dom & got compile error whether that module is not found. Then I installed it separately. Then got this error.

Uncaught Error: useHref() may be used only in the context of a <Router> component.

My code:

index.js

import React from 'react';
import ReactDOM from 'react-dom';
import './index.css';
import NavBar from './components/navbar';
import reportWebVitals from './reportWebVitals';

ReactDOM.render(
  <React.StrictMode>
    <NavBar />
  </React.StrictMode>,
  document.getElementById('root')
);

reportWebVitals();

navBar.jsx

import React from "react";
import {Link} from 'react-router-dom';

const NavBar = () => {
  return (
    <ul>
      <li>
        <Link to="/">Home</Link>
      </li>
      <li>
        <Link to="/products">Products</Link>
      </li>
    </ul>
  );
};

export default NavBar;

products.jsx

import React from "react";

class Products extends React.Component {

  render() {
    return (
      <div>
        <h1>Products</h1>
      </div>
    );
  }
}

export default Products;

Advertisement

Answer

Before you can use the link tags, you first need to create a react router parent called <Routes> (v6) or <BrowserRouter> & <Switch> (v5). In this parent you can define your routes.

View this example:

https://stackblitz.com/github/remix-run/react-router/tree/main/examples/basic?file=src%2FApp.tsx

User contributions licensed under: CC BY-SA
7 People found this is helpful
Advertisement