Ming Soon Ming Soon -4 years ago 246
React JSX Question

'onEnter' hook for Universal Router

With the

, you can abort transition or redirect to the other route when a certain condition meets using the
onEnter()
hook.

Is there any equivalent feature for the
Universal Router
so that I can listen for route changes and redirect users to other pages (for example, to the login page for guest users)?

Answer Source

You can make use of history and then check for the condition in the action of a route, which is pretty much the equivalent of react-router's onEnter. Here's an example:

// Indicator if user is logged in or not.
// const USER = { name: 'Eric' };
const USER = null;

// Create browser history.
const history = window.History.createBrowserHistory();

// Set up routes.
const routes = [
  {
    path: '/settings',
    action: context => {
      // If the user is signed in, show settings, otherwise redirect to login.
      if (!USER) history.push('/login');
      return <h1>Private Settings for {USER.name}</h1>;
    }
  },
  { path: '/login', action: () => <h1>Login</h1> },
  { path: '*', action: () => <h1>Not Found</h1> }
];

// Listen to route changes, re-render with Universal Router when needed.
const unlisten = history.listen((location, action) => {
  UniversalRouter.resolve(routes, {
    path: location.pathname
  }).then(component => {
    ReactDOM.render(component, document.getElementById('root'));
  });
});

// Go to settings on default.
history.push('/settings');

On JSBin.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download