Home > OS >  React throw error while using ReactRouter useLocation
React throw error while using ReactRouter useLocation

Time:10-03

enter image description here

Have an error about useContext while use React Router useLocation hook.

I'm trying to get info about page current location, with useLocation, and getting this error:

useContext is undefined.

import React from 'react';
import Welcome from './Components/Welcome/Welcome';
import {
    BrowserRouter as Router,
    Link,
    Route,
    Switch,
    Redirect,
    useLocation,
} from 'react-router-dom'
import app from "./firebase"

const  App = () => {
let location = useLocation()

  return (
    <div className="App">
      <Router>
        
          
          <Route path = "/welcome">
          <Welcome  />
          </Route>
          
          <Route path="/ui">
        
          <UI/>
        </Route>
      
      </Router>
    </div>
  );
}

const UI = () => {
  return(
    <h1>UI i am</h1>
  )
}

export default App;

package-json: enter image description here

CodePudding user response:

useLocation hooks must be used inside of BrowserRouter but you are defining it before defining your BrowserRouter (which is defined as Router)

First, define your Router, assume we have one page/view in our example:

const  App = () => {
  return (
    <BrowserRouter>
        <Route path = "/welcome">
           <Welcome  />
        </Route>
   </BrowserRouter>
  );
}

Now, in the Welcome:

const Welcome = () => {
   let location = useLocation()
   
   return (
       // rest of your codes
   )
}
  • Related