Documentation

Report Edit

Router

Cx features built-in routing functionality. This enables building complex single page applications and retain classic URL based navigation. There are a few classes used to implement routing and navigation:

  • Url
  • Route
  • Sandbox
  • History
  • Link

Both hash-based and pushState based navigation modes are supported.

Url

import {Url} from 'cx/ui';

The Url helper class offers methods for working with url paths.

It's crucial to initialize the base path before using other methods. Default base path is set to / which works only if the application is not hosted in a subdirectory. Otherwise, call Url.setBase('/path-to-the-app/').

Methods
Url.setBase(base)

Sets the base path of the application.

Url.isLocal(path)

Checks if the given path is local.

Url.resolve(path)

Resolves ~/ in the given path. If a match is found it is replaced with the application path.

Url.setBaseFromScript(scriptPath)

Sets the base path of the application by examining DOM script elements. If the src property matches the given path, the base is used as the application path base.

Url.unresolve(path)

Takes a given relative or absolute path and returns tilde based path.

Routes
Url.setBase('/docs/');
Url.setBaseFromScript('~/app.js');
Url.isLocal('/docs/'); // true
Url.isLocal('/app/'); // false
Url.resolve('~/page'); // /docs/page
Url.unresolve('/docs/page'); // ~/page
Url.unresolve('https://cxjs.io/docs/page'); // ~/page
Copied!
import {Route} from 'cx/widgets';

The Route widget is a pure container element which renders only if current url matches the assigned route.

PropertyDescriptionType
params

Params binding. Matched route parameters will be stored inside.

string
route
path

Target route, e.g. ~/user/:userId. Use ~/ to denote the application root path and +/ in nested routes to append to the parent route.

string
url

Url binding. Bind this to the global url variable.

string
prefix

Match route even if given route is only a prefix of the current url. This is used if a route contains nested subroutes.

boolean
Index
<Route url-bind="url" route="~/about">
    About
</Route>
<Route url-bind="url" route="~/intro" prefix>
    Intro
</Route>
<Route url-bind="url" route="+/nested">
    Nested (~/intro/nested)
</Route>
Copied!

Routes support parameters, splats and optional parts. For more details, check the route-parser library.

Redirect Routes

import {RedirectRoute} from 'cx/widgets';

Redirect routes redirect to another page when matched.

RedirectRoute
<RedirectRoute url-bind="url" route="~/" redirect="~/intro/about"/>
Copied!

Redirect routes use the replaceState method of the History interface, so navigating back after redirection will not return to the redirected page.

import {Sandbox} from 'cx/widgets';

Sandbox component is primarily used to isolate data between different pages. Page data is preserved on navigation and it can be restored if the user goes back to the same page.

Sandbox
<Sandbox key-bind="url" storage-bind="pages">
    <Route url-bind="url" route="~/about">
        <TextField value-bind="$page.text" />
    </Route>
</Sandbox>
Copied!
import {History} from 'cx/ui';

The History class is used for working with HTML5 pushState navigation.

Methods
History.addNavigateConfirmation(callback, permanent)

Instructs the router to execute the given callback to confirm leaving the current page. Return value should be a boolean value or a promise. The callback is executed only for the current page, unless permanent argument is set to true. See the example below.

History.connect(store, bind)

Initializes a link between browser's location and store variable pointed by the bind argument.

History.pushState(state, title, url)

Performs navigation to a new location pointed by the url parameter, without refreshing the page.

History.reloadOnNextChange()

Instructs the router to reload the page on next navigation. This is commonly used with service workers.

History.replaceState(state, title, url)

Performs navigation to a new location pointed by the url parameter. Current location will not be saved in browser's history.

History.subscribe(callback)

Subscribe to location changes (navigation). Useful for setting up page tracking (e.g. Google Analytics) on CxJS apps. The function returns a function which can be used to unsubscribe.

History
History.connect(store, 'url');

History.subscribe(url => {
    if (window.ga) {
        ga('set', 'page', url);
        ga('send', 'pageview');
    }
});
Copied!

Please note that fallback mechanism for browsers which do not support pushState navigation is standard navigation (full page load).

The following example illustrates the use of History.addNavigateConfirmation to ask the user for confirmation before leaving the page.

Confirmation
<Button
    onClick={(e, {store}) => {
        History.addNavigateConfirmation(
            url => MsgBox
                .yesNo('Are you sure you want to leave this page?')
                .then(result => result == 'yes')
        );
        store.set('$page.confirmation', true);
    }}
    text="Add Confirmation"
/>
<p ws visible-expr="!!{$page.confirmation}">
    Good. Now try navigating to <a href="~/concepts/outer-layouts">some other page</a>.
</p>
Copied!Cx Fiddle
import {Link} from 'cx/widgets';

The Link widget is a replacement for anchor elements when pushState based navigation is used.

PropertyDescriptionType
activeClass

Additional CSS class to be applied to the element when it's active.

string/object
activeStyle

Additional CSS style to be applied to the element when it's active.

string/object
confirm

Confirmation text or configuration object. See MsgBox.yesNo for more details.

string/object
enabled

Set to false to disable the button. Do not use both enabled and disabled on the same widget.

boolean
href

Url to the link's target location. The link should start with ~/ or #/ for pushState/hash based navigation. The +/ prefix can be used to build a URL relative to the parent route.

string
inactiveClass

Additional CSS class to be applied to the element when it's not active.

string/object
inactiveStyle

Additional CSS style to be applied to the element when it's not active.

string/object
match

Accepted values are equal, prefix and subroute. Default is equal which means that url must exactly match href in order to consider the link active. In prefix mode, if href is a prefix of url, the link is considered active. The subroute mode is similar to prefix mode, except that the href must be followed by a forward slash /, indicating a subroute.

string
pressed

If true button appears in pressed state. Useful for implementing toggle buttons.

boolean
target

This attribute specifies where to open the linked document.

string
url

Binding to the current url location in the store. If href matches url, additional CSS class active is applied.

string
autoFocus

Set to true to automatically focus the element when mounted.

boolean
baseClass

Base CSS class to be applied to the element. Default is 'link'.

string
class
className

Additional CSS classes to be applied to the element. If an object is provided, all keys with a "truthy" value will be added to the CSS class list.

string/object
disabled

Set to true to disable the link.

boolean
dismiss

If set to true, the Button will cause its parent Overlay (if one exists) to close. This, however, can be prevented if onClick explicitly returns false.

boolean
focusOnMouseDown

Determines if button should receive focus on mousedown event. Default is false, which means that focus can be set only using the keyboard Tab key.

boolean
icon

Name of the icon to be put on the left side of the button.

string
innerHtml
html

HTML to be injected into the element.

string
items
children

List of child elements.

array
layout

Define an inner layout.

string/object
mod

Appearance modifier. Cx ships with primary and danger mods.

string/array
outerLayout

Defines the outer layout which wraps the widget.

widget
plainText

Set to true to avoid converting inner strings to templates. Default is false.

boolean
preserveWhitespace
ws

Keep whitespace in text based children. Default is false. See also trimWhitespace.

boolean
putInto
contentFor

Used with outer layouts. Specifies the name of the content placeholder which should render the widget.

string
style

Style object applied to the wrapper div. Used for setting the dimensions of the element.

string/object
submit

Add type="submit" to the button.

boolean
tag

HTML tag to be used. Default is button.

string
text
innerText

Inner text contents.

string
tooltip

Tooltip configuration. For more info see Tooltips.

string/object
trimWhitespace

Remove all whitespace in text based children. Default is true. See also preserveWhitespace.

boolean
vdomKey

Key that will be used as the key when rendering the React component.

string
visible
if

Visibility of the widget. Defaults to true.

boolean
<Link href="~/about">About<Link>