Search code examples
reactjsreact-routerreact-router-domreact-context

React router and context


I am using the useContext and react-routers in my project which is structured like this:

<AppProvider>
  <Router>
    <Switch>
      <Route exact path="/">
        <Home />
      </Route>
      <Route exact path="/about">
        <About />
      </Route>
    </Switch>
  </Router>
</AppProvider>

I want to navigate to a path from my context file but I cannot since it is outside the router. What is the best way to achieve this?

What I want (in AppProvider component in context.js):

let history = useHistory()

useEffect(() => {
  const unsubscribe = projectAuth.onAuthStateChanged((authUser) => {
    if (authUser) {
      history.push("/about");
    }
  });
  return unsubscribe;
}, []);

Solution

  • You can restructure your layout to wrap AppProvider with Router and then everything will work since AppProvider will then get the history object used by Router when you use useHistory

    <Router>
      <AppProvider>
        <Switch>
          <Route exact path="/">
            <Home />
          </Route>
          <Route exact path="/about">
            <About />
          </Route>
        </Switch>
      </AppProvider>
    </Router>