Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to emulate window.location with react-router and ES6 classes

I'm using react-router, so I use the <Link /> component for my links throughout the app, in some cases I need to dynamically generate the link based on user input, so I need something like window.location, but without the page refresh.

I found this little note - (https://github.com/rackt/react-router/issues/835) - i tried using this.context.router.transitionTo(mylink) but I'm having issues with context...

which led me to (https://github.com/rackt/react-router/issues/1059), however context returns and empty object, so when I try todo something like: this.context.router.transitionTo(mylink); I get Cannot read property 'transitionTo' of undefined (if I try to do something like set this.context = context within the constructor).

Not to drag on, but I'm also weary of messing too much with context as it is undocumented on purpose as it's still a work in progress, so I've read.

Has anyone come across a similar issue?

like image 689
Ben Avatar asked Jul 21 '15 12:07

Ben


People also ask

How do I access my location in React router?

Use the useLocation() hook to get the current route with React Router, e.g. const location = useLocation() . The hook returns the current location object. For example, you can access the pathname as location.

How do I redirect a window in React?

push("URL_HERE") whenever a user performs a certain action, in our example we will use a button click. Now when the user clicks on the button we will push a new relative URL into the history which will cause the user to be redirected to the desired page.

How do you get the location path in React?

Since React is based on regular JavaScript, you can access the location property on the window interface. To get the full path of the current URL, you can use window. location. href , and to get the path without the root domain, access window.


2 Answers

After wasting time with react router, I finally switch to basic javascript.

  1. Create a component for your redirect:

    Route path="*" component={NotFound}

  2. In the component use window.location to redirect:

     componentDidMount() {       if (typeof window !== 'undefined') {            window.location.href = "http://foo.com/error.php";       }  } 
like image 108
Priyanshu Chauhan Avatar answered Oct 22 '22 23:10

Priyanshu Chauhan


Found a solution here: https://github.com/rackt/react-router/issues/975, and here: https://github.com/rackt/react-router/issues/1499

Needed in constructor:

class SidebarFilter extends React.Component {      constructor(props, context) {         super(props, context); 

Also need to add a static property:

SidebarFilter.contextTypes = {   router: React.PropTypes.func.isRequired }; 

Then I could call:

this.context.router.transitionTo(/path-to-link); 
like image 41
Ben Avatar answered Oct 22 '22 23:10

Ben