# @stencil/router

> Stencil Router

Latest version **1.0.1** (published 2019-06-08) · MIT license · 0 weekly downloads

> **Deprecated.** This package is deprecated.

## Install

```sh
npm install @stencil/router
pnpm add @stencil/router
yarn add @stencil/router
bun add @stencil/router
```

## Health

**Score 10/100 (F)** — status: deprecated.

Negative: deprecated.

## Facts

| | |
|---|---|
| Version | 1.0.1 |
| Published | 2019-06-08 |
| First published | 2017-08-14 |
| Weekly downloads | 0 |
| License | MIT |
| TypeScript types | bundled |
| Module format | ESM + CommonJS |
| Dependencies | 1 |
| Unpacked size | 1.2 MB |
| Known vulnerabilities | 0 |
| Install scripts | no |
| GitHub stars | 187 |
| Author | Ionic Team |
| Maintainers | adamdbradley, brandyscarney, camwiegert, dwieeb, ionicjs, jthoms1, kensodemann, manucorporat, maxlynch, mhartington, nhyatt |

## Links

- npm: https://www.npmjs.com/package/@stencil/router
- Repository: https://github.com/ionic-team/stencil-router
- Issues: https://github.com/ionic-team/stencil-router
- npm.io page: https://npm.io/package/@stencil/router

## Dependencies (1)

- [@stencil/state-tunnel](https://npm.io/package/@stencil/state-tunnel.md) ^1.0.1

## Recent versions

- 1.0.1 (latest) — 2019-06-08
- 2.0.0-2 (next) — 2021-01-23
- 1.0.0 (one) — 2019-06-02
- 2.0.0-1 — 2020-10-19
- 2.0.0-0 — 2020-10-17
- 1.0.0-1 — 2019-05-16
- 1.0.0-0 — 2019-05-15
- 0.3.4-2 — 2019-04-19
- 0.3.4-1 — 2019-04-11
- 0.3.4-0 — 2019-04-02
- 0.3.3-1 — 2019-04-02
- 0.3.3-0 — 2019-04-02
- 0.3.3 — 2019-01-25
- 0.3.2 — 2019-01-07
- 0.3.1 — 2018-10-15
- … 86 more at https://npm.io/package/@stencil/router/versions

## README

# @stencil-community/router

Stencil Router V2 is an experimental new router for stencil that focus in:

- **Lightweight** (600bytes)
- **Treeshakable** (not used features are not included in the final build)
- **Simple**, provide the bare mininum but it make it extendable with hooks.
- **No DOM**: Router is not render any extra DOM element, to keep styling simple.
- **Fast**: As fast and lightweight as writing your own router with if statements.

## How does it work?

This router backs up the `document.location` in a `@stencil/store`, this way we can respond to changes in document.location is a much simpler, way, not more subscribes, no more event listeners events to connect and disconnect.

Functional Components are the used to collect the list of routes, finally the `Switch` renders only the selected route.


## Install

```bash
npm install @stencil-community/router --save-dev
```

## Examples

```tsx
import { createRouter, Route } from '@stencil-community/router';

const Router = createRouter();

@Component({
  tag: 'app-root',
})
export class AppRoot {

  render() {
    return (
      <Host>
        <Router.Switch>

          <Route path="/">
            <h1>Welcome</h1>
            <p>Welcome to the new stencil-router demo</p>
          </Route>

          <Route path={/^\/account/}>
            <app-account></app-account>
          </Route>

        </Router.Switch>
      </Host>
    );
  }
}
```

### Redirects
```tsx
<Host>
  <Router.Switch>

    <Route path="/" to="/main"/>
    <Route path={/^account/} to="/error"/>

  </Router.Switch>
</Host>
```

### Params

Route can take an optional `render` property that will pass down the params. This method should be used instead of JSX children.

Regex or functional matches have the chance to generate an object of params when the URL matches.


```tsx
import { createRouter, Route, match } from '@stencil-community/router';

const Router = createRouter();

<Host>
  <Router.Switch>

    <Route
      path={/^acc(ou)nt/}
      render={(params) => (
        <p>{params[1]}</p>
      )}
    />

    <Route
      path={match('/blog/:page')}
      render={({page}) => <blog-post page={page}>}
    />

    <Route
      path={(url) => {
        if (url.includes('hello')) {
          return {user: 'hello'}
        }
        return undefined;
      }}
      render={({user}) => (
        <h1>User: {user}</h1>
      )}
    />

  </Router.Switch>
</Host>
```

A simple router, inspired by React Router v4, for Stencil apps and vanilla Web Component apps.
### Links

The `href()` function will inject all the handles to an native `anchor`, without extra DOM.

```tsx
import { createRouter, Route, href } from '@stencil-community/router';

const Router = createRouter();

<Host>
  <Router.Switch>

    <Route path="/main">
      <a {...href('/main')} class="my-link">Go to blog</a>
    </Route>

    <Route path="/blog">
      <a {...href('/main')}>Go to main</a>
    </Route>

  </Router.Switch>
</Host>
```


### Dynamic routes (guards)

```tsx
@Component({
  tag: 'app-root',
})
export class AppRoot {

  @State() logged = false;
  render() {
    return (
      <Host>
        <Router.Switch>

          {this.logged && (
            <Route path="/account">
              <app-account></app-account>
            </Route>
          )}

          {!this.logged && (
            <Route path="/account" to="/error"/>
          )

        </Router.Switch>
      </Host>
    );
  }
}
```

### Subscriptions to route changes

Because the router uses `@stencil/store` its trivial to subscribe to changes in the locations, activeRoute, or even the list of routes.

```tsx
import { createRouter, Route } from '@stencil-community/router';

const Router = createRouter();

@Component({
  tag: 'app-root',
})
export class AppRoot {
  componentWillLoad() {
    Router.onChange('url', (newValue: InternalRouterState['url'], _oldValue: InternalRouterState['url']) => {
      // Access fields such as pathname, search, etc. from newValue

      // This would be a good place to send a Google Analytics event, for example
    });
  }

  render() {
    const activePath = Router.state.activeRoute?.path;

    return (
      <Host>
        <aside>
          <a class={{'active': activePath === '/main'}}>Main</a>
          <a class={{'active': activePath === '/account'}}>Account</a>
        </aside>

        <Router.Switch>

          <Route path="/main">
            <h1>Welcome</h1>
            <p>Welcome to the new stencil-router demo</p>
          </Route>

          <Route path='/account'>
            <app-account></app-account>
          </Route>

        </Router.Switch>
      </Host>
    );
  }
}
```
The routes state includes:
```tsx
  url: URL;
  activeRoute?: RouteEntry;
  urlParams: { [key: string]: string };
  routes: RouteEntry[];
```

[wiki]: https://github.com/stencil-community/stencil-router/wiki

[npm-badge]: https://img.shields.io/npm/v/@stencil-community/router.svg
[npm-badge-url]: https://www.npmjs.com/package/@stencil-community/router

---
_Source: https://npm.io/package/@stencil/router · Machine-readable twin of the npm.io package page. Health data is recomputed on every publish._
