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

Created at 04-Nov-2022 , By samar

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

In this session, we will try our hand at solving the "Uncaught Error: useHref() may be used only in the context of a component".

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 version 18.0.0 which is used in routing in react app. To install the package you have to run npm i react-router-dom command in your terminal.

Back to code snippet queries related react

If you like what you are reading, please consider buying us a coffee ( or 2 ) as a token of appreciation.

Buy Me A Coffee

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.