Uncaught Error: useHref() may be used only in the context of a <Router> component
Uncaught Error: useHref() may be used only in the context of a
In this session, we will try our hand at solving the "Uncaught Error: useHref() may be used only in the context of a
We will use below code in this lesson to attempt to solve the error Uncaught Error: useHref() may be used only in the context of a <Router> component in our react app.
Before going to the solution of the error I would like to discuss the reason behind it. I was trying to add an anchor tag using (<Link>) in my react app. But I got the above error because I was not using the <Router> component. You have to wrap all the <Link> inside the <Router> component to get rid of the error.
To avoid the above error, you have to install react-router-dom package using npm install react-router-dom command in your terminal. After that you have to import the <Router>
using import method import { BrowserRouter as Router, Link } from 'react-router-dom';
and wrap all the links in router component.
-
Use <Link> with <Router> in react
Import the react router dom with react.
import React from 'react'; import { BrowserRouter as Router, Link } from 'react-router-dom';
Now you have to wrap all the <Link> with <Router> component
<Router> <ul className="App-header"> <li> <Link to="/">Home</Link> </li> <li> <Link to="/about">About Us</Link> </li> </ul> </Router>
Your Complete source code.
import React from 'react'; import { BrowserRouter as Router, Link } from 'react-router-dom'; const App = () => { return ( <div className="App"> <Router> <ul className="App-header"> <li> <Link to="/">Home</Link> </li> <li> <Link to="/about">About Us</Link> </li> </ul> </Router> </div> ); }; export default App;
Additional Info
I am using
react-router-dom
package in my react app version18.0.0
which is used in routing in react app. To install the package you have to runnpm i react-router-dom
command in your terminal.
If you like what you are reading, please consider buying us a coffee ( or 2 ) as a token of appreciation.
Don't forget to share this article! Help us spread the word by clicking the share button below.
We appreciate your support and are committed to providing you valuable and informative content.
We are thankful for your never ending support.
Random Code Snippet Queries: React
- We're unable to detect target browsers. react app
- React-dom.development.js:86 Warning: validateDOMNesting(...):
- Warning: ReactDOM.render is no longer supported in React 18. Use createRoot instead
- Module Not Found: Can’T Resolve ‘Jquery’ In React
- How do I link to an external URL in React?
- Module not found: Error: Can't resolve 'prop-types'
- How to pass dynamic URL to Link in react ?
- Get the ID from a URL in React and React Router