Skip to content

Tomekmularczyk/react-router-global-history

Folders and files

NameName
Last commit message
Last commit date

Latest commit

 

History

22 Commits
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 

Repository files navigation

react-router-global-history npm version

This is a simple helper library to live alongside react-router-4 to help you access history object from the wherever file in your application (like in redux actions).

You simply need to mount component on top of your application like:

import { BrowserRouter } from 'react-router-dom';
import { ReactRouterGlobalHistory } from 'react-router-global-history';

function render() {
  ReactDOM.render(
    <BrowserRouter>
        <div>
            <ReactRouterGlobalHistory />
            //.....
        </div>
    </BrowserRouter>
    document.getElementById('app'),
  );
}

This will initialize internal history variable (in constructor) with the one provided by withRouter HOC. Which means you can import it wherever in the app like:

import getHistory from 'react-router-global-history'; 

export const goToPage = () => (dispatch) => {
  dispatch({ type: GO_TO_SUCCESS_PAGE });
  getHistory().push('/success');
};

That's it! But there's one catch. You need to call getHistory() after component has been mounted. For example initialization of redux happens before app renders so if you try to access history like: reducer.js:

import getHistory from 'react-router-global-history'; 

const history = getHistory(); // error!

... you will get an error. So make sure you call it when the ReactRouterGlobalHistory component has already been mounted!

About

Access react-router-4 history outside of the component.

Resources

Stars

Watchers

Forks

Packages

No packages published