WebApps 2

router

Router provides methods to facilitate working with URLs in a client context.

Methods

router.getUrl(path [, queryStringParameters])

Returns a URL given a path. Provide queryStringParameters as an object to include query string parameters. The URL will match configured paths in the server side context of your app.

// server context
import router from '@sitevision/api/common/router';

router.post('/purchase', (req, res) => {
   res.json({});
});
// client context
import router from '@sitevision/api/common/router';
import requester from '@sitevision/api/client/requester';

const doPost = (options) => {
   requester
      .doPost({
         url: router.getUrl('/purchase'), // match '/purchase' in server side context
         data: options.data,
      })
      .then((response) => {
         ...
      });
};

router.getStandaloneUrl(path [, queryStringParameters])

Returns a URL that will execute a route standalone, i.e. it will not be part of page rendering. This is very useful when you only want to target your route without any side effects. Typical use cases are delivering a file from a route or redirecting when a form has been posted.

Example of a standalone URL being used to execute a route:

// component example
import * as React from 'react';
import requester from '@sitevision/api/client/requester';
import router from '@sitevision/api/common/router';

const App = () => {
   const getJSON = () => {
      requester
         .doGet({
            url: router.getStandaloneUrl('/json'),
         })
         .then((data) => {
            console.log(JSON.stringify(data));
         });
   };

   return <button onClick={getJSON}>Log JSON</button>;
};

export default App;
// server context
// ...
router.get('/json', (req, res) => {
   res.json({
      name: 'Grodan Boll',
      age: 33,
   });
});
// ...

router.navigate(url [, options])

Updates the URL (History API) and triggers path and/or query changes. Defaults to pushState navigation. Set the replace option to true to perform a replaceState navigation. Pass a queryParams object in the options object to update query string parameters in the URL.

import router from '@sitevision/api/common/router';

// updates URL
router.navigate(router.getUrl('/properties'));

// replaceState
router.navigate(router.getUrl('/properties'), {
   replace: true,
});

Pass an empty string as URL to update query string parameters while maintaining current path.

router.navigate('', {
   queryParams: {
      layout: options.layout,
   },
});

router.parseQueryString()

Returns current query string (location.search) as an object. WebApp specific parameters (sv.target and sv.<portletId>.router) are omitted from the object.

//?sv.target=12.52ed0541665c9934cb5&sv.12.52ed0541665c9934cb5.route=/test&foo=bar
router.parseQueryString(); // {foo: 'bar'}