Szilard Ban
Szilard Ban

Reputation: 191

Why can't I use useLocation in BrowserRouter in React?

I have a react app, with react-router v6 used as the routing system. I have tried several ways of listening to route changes, as I have a function to run every time, yet I couldn't manage to get it working. The code sample below, which I believe is the intended way of using the useLocation hook, runs to an error, "useLocation can only be used in the context of router, yet I believe BrowserRouter creates a router, it is even showed in the error message, yet I still can't use it. The error can be seen in the screenshot.

function App() {
    const location = useLocation()
    React.useEffect(() => { console.log(location) }, [location])
    return (
        <Provider store={store}>
                <ThemeProvider theme={theme}>
                    <CssBaseline />
                    <Main />
                </ThemeProvider>
        </Provider>
    )
}

ReactDOM.render(<BrowserRouter><App /></BrowserRouter>, document.getElementById('app'));

The error shown by the browser

Error: useLocation() may be used only in the context of a Router component. The above error occurred in the App component: in App in Router (created by BrowserRouter) in BrowserRouter

Upvotes: 1

Views: 1835

Answers (2)

stackersunited
stackersunited

Reputation: 9

You can't use it from within the same component that puts the Router or BrowserRouter into the tree.

I had a similar problem and kept the BrowserRouter in App.js but moved the switch and routes to a separate 'Routes' component that also has uses the useLocation hook.

Upvotes: 1

Kybarg
Kybarg

Reputation: 43

My guess you import BrowserRouter from react-router and it is not version 6 while useLocation() is imported from react-router-dom of version 6

Upvotes: 1

Related Questions