---
url: https://lit-ui-router.dev/guides/routed-components.md
description: >-
  Read a state's params in its routed component, type its resolves, code-split
  the component's element module with a resolve or a lazyLoad future state, and
  reach the element a view rendered
---

# Routed Components

A routed component gets its inputs from `<ui-view>`, which renders it with
[`UIViewInjectedProps`](/reference/lit-ui-router/types/UIViewInjectedProps): the
`router`, the `transition` that rendered the view, and the state's
`resolves`. This guide covers what every routed component meets: reading its
state's params and typing its resolves, loading its own element module only
when the state is entered, and how the page reaches the element a view
rendered.

## Reading params

Declare the params the component needs as a resolve on its state. The resolve
depends on `$transition$`, reads the value once, and hands the component a
named, typed input:

```ts
import type { Transition } from '@uirouter/core';
import type { LitStateDeclaration } from 'lit-ui-router';

interface UserResolves {
  userId: string;
}

const userState = {
  name: 'user',
  url: '/users/:id',
  resolve: [
    {
      token: 'userId',
      deps: ['$transition$'],
      resolveFn: ($transition$: Transition) => $transition$.params().id,
    },
  ],
  component: UserDetail,
} satisfies LitStateDeclaration<UserResolves>;
```

```ts
import { LitElement, html } from 'lit';
import { property } from 'lit/decorators.js';
import type { UIViewInjectedProps } from 'lit-ui-router';

class UserDetail extends LitElement {
  @property({ attribute: false })
  uiViewProps?: UIViewInjectedProps<UserResolves>;

  render() {
    return html`<h1>User ${this.uiViewProps?.resolves.userId}</h1>`;
  }
}
```

`uiViewProps` is the property's name from `lit-ui-router` 1.20. `<ui-view>`
also assigns the same props to `_uiViewProps`, the deprecated name earlier 1.x
releases wrote, so a class that declares only that name keeps working.

The router owns both names on a routed class. It assigns them on every render,
so a class cannot keep its own data there or define either as a getter without
a setter.

The same resolve can fetch the record instead of passing the id through, so
the component renders with its data already loaded. The sample app's
`contacts.contact` state
([contacts/states.ts](https://github.com/simshanith/lit-ui-router/blob/main/apps/sample-app-shared/src/app/contacts/states.ts))
resolves the contact from its `contactId` param this way.

Reading `router.globals.params` from the component instead ties it to whatever
state is current, not the state it was rendered for, and gives it no type.

A template function can read `props.transition.params()` directly for a quick
view; the [`RoutedLitTemplate`](/reference/lit-ui-router/types/RoutedLitTemplate)
reference shows that form.

### Params that change without re-entering the state

A non-dynamic param change exits and re-enters the state, so the component is
rebuilt with fresh resolves. A **dynamic** param keeps the component, and its
resolves keep the values they had when it was created. Read changed values in
[`uiOnParamsChanged`](./component-lifecycle#uionparamschanged-react-to-dynamic-parameters).

## Typing resolves

`LitStateDeclaration<T>` takes the resolves type as a generic, defaulting to
`Record<string, any>`. A view receives `T` as an argument, so the check runs in
reverse: a view that requires a resolve does not fit the default, and TypeScript
reports the error at `component:` rather than at the generic.

```ts
const GalleryView: RoutedLitTemplate<{ manifest: Manifest }> = (props) =>
  html`<p>${props.resolves.manifest.sheets.length}</p>`;

const states: LitStateDeclaration[] = [
  { name: 'gallery', url: '/', component: GalleryView }, // TS2322 at component:
];
```

Two shapes type-check:

* **Thread the generic** onto the declaration: `LitStateDeclaration<{ manifest: Manifest }>[]`.
  A bare `RoutedLitTemplate` view still fits beside the typed one.
* **A table mixing resolve shapes** threads one type alias that covers every view,
  such as `GalleryResolves & SheetResolves`. Each view keeps its own required
  members. An alias with every member optional also fits, at the cost of `?.` at
  each use inside the views.

The names are adapted from [the Altitude Atlas](https://atlas.lit-ui-router.dev), whose
gallery and sheet
[views](https://github.com/simshanith/lit-ui-router/blob/52b1984806b12fb3bbd11fa47a5cf622af1fca4d/www/atlas.lit-ui-router.dev/app/src/views.ts#L1448-L1449)
use the last of these, an alias with every member optional.

## Lazy-loading a route's element

Importing the element module inside `component` without awaiting it renders
an undefined element that upgrades whenever the chunk arrives, and a failed
chunk load surfaces as an unhandled rejection:

```ts
component: () => {
  import('./users/users.js'); // not awaited
  return html`<app-users></app-users>`;
},
```

### Await the module in a resolve

Return the import from a resolve. Resolves settle before the state is entered,
so the element is defined by the time `<ui-view>` renders it, and a failed
import rejects the transition, where
[transition hooks](./route-guards) and `stateService.defaultErrorHandler` see
it:

```ts
const usersState = {
  name: 'users',
  url: '/users',
  resolve: [
    {
      token: 'usersElement',
      resolveFn: () => import('./users/users.js'),
    },
  ],
  component: () => html`<app-users></app-users>`,
} satisfies LitStateDeclaration;
```

The [Hello Galaxy tutorial](/tutorial/hellogalaxy) loads
`@google/model-viewer` for one state the same way.

### Lazy-load a whole feature with a future state

When a feature owns several states, register one placeholder whose name ends
in `.**` and whose `lazyLoad` imports a module exporting `states`. The first
navigation into the URL prefix loads the module, registers its states in
place of the placeholder, and retries the transition:

```ts
const contactsFutureState = {
  parent: 'app',
  name: 'contacts.**',
  url: '/contacts',
  lazyLoad: () => import('./contacts/states.js'),
};
```

The lazy-loaded module exports a `states` array:

```ts
// contacts/states.ts
import type { LitStateDeclaration } from 'lit-ui-router';
import { ContactsView } from './ContactsView.js';

export const states: LitStateDeclaration[] = [
  {
    name: 'contacts',
    parent: 'app',
    url: '/contacts',
    component: ContactsView,
  },
];
```

The state modules import their components statically, so the elements arrive
in the same chunk. The sample app splits contacts, prefs and messages this way
([main/states.ts](https://github.com/simshanith/lit-ui-router/blob/main/apps/sample-app-shared/src/app/main/states.ts)).
If you also register an `otherwise` rule for 404s, a mistyped URL under a `.**`
prefix still lazy loads the feature, and without the extra hook shown in
[Unmatched URLs (404)](./unmatched-urls#caveat-lazy-loaded-future-states) the
404 does not render.

## The routed element

`<ui-view>` renders into its light DOM, so page CSS and queries reach the
routed component. The view's own children are internal: next to the routed
markup they hold Lit's part markers and, while one component replaces
another, the element on its way out. Reach the routed element through the view
instead of `firstElementChild` or child selectors:

* [`routedElement`](/reference/lit-ui-router/components/UiView) is the
  element the routed component rendered: a class component's instance, or the
  first element a template component rendered. It is `null` while the view
  shows its [fallback content](./view-fallback-content).
* The same element carries a `routed` attribute, for CSS.

```css
ui-view > [routed] {
  min-height: 100%;
}
```

A template component marks only its first element. When its template has
several top-level elements, wrap them in one element so a `[routed]` rule
reaches all of it.

```ts check
const view = document.querySelector('ui-view');
view?.routedElement?.scrollIntoView();
```

When a state change replaces one class component with another, `<ui-view>`
inserts the incoming element next to the outgoing one, and removes the
outgoing element once the incoming one has completed its first update. The
view keeps its content in between, so a layout read during the swap does not
see a collapsed page. Only class-to-class swaps hold the outgoing element:
fallback content and template components are replaced in the same update.

`routedElement` points at the incoming element once the view renders it, and
the `routed` attribute moves to it when that view update commits. Both
change before the incoming element has rendered, so during the hold a
`[routed]` rule styles the incoming element, not the outgoing one still on
screen.

A template component can also swap its elements without the view updating,
as `until()` does when its content replaces a placeholder. `routedElement`
returns the new first element at once, and the `routed` attribute follows a
microtask later, so code that reads `[routed]` in the same task as the swap
still finds the old element.

The attribute is set when the view renders in the browser, so a prerendered
page carries it once its views have hydrated.
