Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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?

like image 881
yadielar Avatar asked Dec 14 '25 03:12

yadielar


1 Answers

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 />
}
like image 174
Muhammad Ali Avatar answered Dec 16 '25 20:12

Muhammad Ali



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!