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.
JavaScript
x
2
1
Uncaught Error: useHref() may be used only in the context of a <Router> component.
2
My code:
index.js
JavaScript
1
15
15
1
import React from 'react';
2
import ReactDOM from 'react-dom';
3
import './index.css';
4
import NavBar from './components/navbar';
5
import reportWebVitals from './reportWebVitals';
6
7
ReactDOM.render(
8
<React.StrictMode>
9
<NavBar />
10
</React.StrictMode>,
11
document.getElementById('root')
12
);
13
14
reportWebVitals();
15
navBar.jsx
JavaScript
1
18
18
1
import React from "react";
2
import {Link} from 'react-router-dom';
3
4
const NavBar = () => {
5
return (
6
<ul>
7
<li>
8
<Link to="/">Home</Link>
9
</li>
10
<li>
11
<Link to="/products">Products</Link>
12
</li>
13
</ul>
14
);
15
};
16
17
export default NavBar;
18
products.jsx
JavaScript
1
15
15
1
import React from "react";
2
3
class Products extends React.Component {
4
5
render() {
6
return (
7
<div>
8
<h1>Products</h1>
9
</div>
10
);
11
}
12
}
13
14
export default Products;
15
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