How can I check if react-router is in context?

Issue

I’m migrating an AngularJS app to React little by little, and I would like to have a custom RouterLink React component that checks if react-router is in context so it can use history, and if not, falls back to usage of good old window.location. But I don’t see any way of checking that in react-router‘s documentation.

I tried using withRouter but it throws when not in context and an ErrorBoundary doesn’t seem to catch the error.

Does anyone know how I could go about doing this?

Solution

There is Router context exposed in react-router package, i.e. __RouterContext, by using that you can check if router is avaiable:

import React, { useContext } from 'react';
import { __RouterContext } from 'react-router';

const MyComponent = (props) => {
  const router = useContext(__RouterContext);

  if (router) {
    // Router context is avaible
  } else {
    // Use window.location as router context is not availble in this component
  }

  return <SomeOtherComponent />
}

Answered By – Muhammad Ali

This Answer collected from stackoverflow, is licensed under cc by-sa 2.5 , cc by-sa 3.0 and cc by-sa 4.0

Leave a Reply

(*) Required, Your email will not be published