Skip to content

VirtualRoute

Class for creating routes with custom activation logic. Useful for implementing:

  • Modal windows routing
  • Feature toggles
  • Conditional UI states
  • Non-URL-based routing scenarios

Unlike standard Route, doesn't depend on URL path. Activation state is determined by custom logic.

Constructor

ts
createVirtualRoute(config?: VirtualRouteConfiguration<TParams>)
new VirtualRoute(config?: VirtualRouteConfiguration<TParams>) // class form

Configuration options:

  • initialParams: initial params for this route
  • checkOpened: Function/value determining if route is open
  • open: Custom open handler
  • close: Custom close handler
  • queryParams: Custom query params implementation

Example:

ts
const ageModalRoute = createVirtualRoute<{ age: number }>({
  initialParams: { age: 0 },
  checkOpened: (route) => !!route.query.showAgeModal,
  open: (params, route) =>
    route.query.update({
      ...params,
      showAgeModal: 'true'
    }),
  close: (route) =>
    route.query.update({
      showAgeModal: undefined
    })
});

Methods and properties

isOpened computed

Indicates whether route is active. Automatically updates when dependencies change.

Example:

ts
const route = createVirtualRoute({
  checkOpened: () => Math.random() > 0.5
});

autorun(() => {
  console.log('Route state:', route.isOpened); // Randomly changes
});

isOpening computed

Indicates if this route is currently in the process of opening.
Returns true when the route status is 'opening'.

isClosing computed

Indicates if this route is currently in the process of closing.
Returns true when the route status is 'closing'.

params observable

Current virtual route parameters. Type is determined by generic type parameter.
Example:

ts
const route = createVirtualRoute<{ userId: string }>();
route.open({ userId: '123' });
route.params?.userId; // '123'

query

Interface for managing query parameters from mobx-location-history package.
Automatically synchronized with current url.

open() action

Activates the route with execution flow:

  1. Updates params/query
  2. Uses custom open handler if provided for change isOpened or sets isOpened `true

close() action

Deactivates the route. Behavior depends on configuration:

  1. Uses custom close handler if provided
  2. Default behavior sets isOpened to false

setOpenChecker() action

Updates the openChecker value with the provided one.
openChecker is a function or a boolean value that determines whether the route is open or not.

isOuterOpened observable.ref

This property is not recommended for detecting the opened state. Use the isOpened property instead.

Indicates the external "opened" state determined by the checkOpened function.
This value is automatically updated when the checkOpened function's dependencies change.

Configuration

Interface: VirtualRouteConfiguration

This is specific object used to detailed configure virtual route.
Here is list of configuration properties which can be helpful:

abortSignal

AbortSignal used to destroy\cleanup route subscriptions

meta

Additional object which can contains meta information

ts
const route = createVirtualRoute({
  meta: {
    memes: true
  }
});

console.log(route.meta?.memes); // true

open()

Custom implementation of open behaviour for this route.
It can be helpful if you need custom open/close behaviour

Will be used default implementation if is not specified:

ts
defaultOpenImplementation = () => true;

Examples:

ts
const route = createVirtualRoute({
  checkOpened: () => !!queryParams.data.yummiesDialog,
  open: () => {
    queryParams.update({ yummiesDialog: true });
    return true
  }
})

close()

Custom implementation of close behaviour for this route
It can be helpful if you need custom open/close behaviour

Will be used default implementation if is not specified:

ts
defaultCloseImplementation = () => false;

Examples:

ts
const route = createVirtualRoute({
  checkOpened: () => !!queryParams.data.yummiesDialog,
  close: () => {
    queryParams.update({ yummiesDialog: false });
    return false
  }
})

checkOpened()

Custom implementation of close/open statement for this route
It can be helpful if you need custom open/close behaviour

Examples:

ts
const route = createVirtualRoute({
  checkOpened: () => !!queryParams.data.yummiesDialog,
})

getAutomatedOpenParams()

Function that returns parameters for automated route opening.
This function is called when the route is automatically opened based on the checkOpened function result.
It should return an object with params and optionally extra properties.

Example:

ts
const route = createVirtualRoute({
  checkOpened: () => !!queryParams.data.modal,
  getAutomatedOpenParams: (route) => {
    return {
      params: { id: queryParams.data.modalId },
      extra: { query: { modal: 'true' } }
    };
  }
})

beforeOpen

Event handler "before opening" a route, required for various checks before the route itself is opened.
With this handler, we can prevent the route from opening by returning false,
or override the navigation to another one by returning

ts
{
  url: string;
  state?: any;
  replace?: boolean;
}

Example:

ts
const route = createVirtualRoute('/foo/bar', {
  beforeOpen: () => {
    if (!auth.isAuth) {
      return false;
    }
  }
})

beforeClose()

Event handler "before closing" a route, required for various checks before the route itself is closed.
With this handler, we can prevent the route from closing by returning false.

Example:

ts
const route = createVirtualRoute({
  checkOpened: () => !!queryParams.data.modal,
  beforeClose: () => {
    if (hasUnsavedChanges) {
      return false; // Prevent closing
    }
  }
})

afterClose()

Calls after close route.

afterOpen()

Calls after open route.

Released under the MIT License.