0.0.45-alpha • Published 2 years ago

@crux/router v0.0.45-alpha

Weekly downloads
-
License
-
Repository
-
Last release
2 years ago

@crux/router

@crux/router is a framework-agnostic, small, fast, TypeScript router for front-end applications.

Installation

npm install --save @crux/router

Usage

import { createRouter } from '@crux/router';

const router = createRouter({
  users: '/users', // example.com/users
  user: '/users/:id', //ex
});

This creates a router with two user routes, one for getting a list of users (e.g. users) and one for getting a single user by id (e.g. users/1).

Setting the base route

createRouter takes a second parameter, which is a string that defaults to ''. Use this to set your base route:

const router = createRouter({
  users: '/users',
  user: '/users/:id',
}, 'api/v2');

Note that leading and trailing slashes are removed from the base, so any of these are valid: /api/v2, api/v2/, /api/v2/.

Transitioning between routes

// Navigate to example.com/users
router.navigate('users');

// Navigate to example.com/users/1
router.navigate('user', { id: 1 });

Reacting to route changes

@crux/router emits events during the route transition. Use router.on(eventType, callback) to register listeners to those events:

Event NameDescription
routeDidChangeRuns immediately as soon as the URL changes. This is the time to start page-in transitions.
readyRuns after any Promises returned from the routeDidChange hook have resolved.
routeChangeFailedRuns if there is an error during route transition.

For example, let's assume we want to add a fadeIn for the new route, and we want to log when each of those animations has happened:

router.on('routeDidChange', ({ next }) => fadeIn(next));

router.on('ready', () => console.log('Fade in finished'));

function fadeIn() {
  return new Promise(resolve => {
    document.body.classList.add('fadeIn'); // Fades in for 1000ms
    
    // Resolve the promise after 1000ms
    setTimeout(() => resolve(), 1000);
  });
}
0.0.45-alpha

2 years ago

0.0.40-alpha

2 years ago

0.0.43-alpha

2 years ago

0.0.41-alpha

2 years ago

0.0.42-alpha

2 years ago

0.0.44-alpha

2 years ago

0.0.38-alpha

2 years ago

0.0.37-alpha

2 years ago

0.0.39-alpha

2 years ago

0.0.36-alpha

2 years ago

0.0.29-alpha

2 years ago

0.0.35-alpha

2 years ago

0.0.23

2 years ago

0.0.30-alpha

2 years ago

0.0.24

2 years ago

0.0.25

2 years ago

0.0.32-alpha

2 years ago

0.0.31-alpha

2 years ago

0.0.28-alpha

2 years ago

0.0.27-alpha

2 years ago

0.0.33-alpha

2 years ago

0.0.26

2 years ago

0.0.26-alpha

2 years ago

0.0.34-alpha

2 years ago

0.1.1-alpha

2 years ago

0.1.0-alpha

2 years ago

0.2.0-alpha

2 years ago

0.0.6

2 years ago

0.0.1

3 years ago