Skip to content

Passing data to routes

Josh Thomas edited this page Jun 6, 2018 · 8 revisions

There are multiple ways that you can pass data to routes and for routes to read that data. This page will provide you with info on each approach and try to help you answer which approach is best for your scenario.

NOTE: This list does not include passing props directly to a route. Info on that can be found in the stencil-route component.


Route Params

Url appearance: /user/12345

Route definition

<stencil-route url="/user/:userId" component="user-detail" />

Consumption of the data with in the route

@Component({
  tag: 'user-detail'
})
export class UserDetail {
  @Prop() history: RouterHistory;
  @Prop() match: MatchResults;

  render() {
    return (
      <div>{this.match.params.userId}</div>
    );
  }
}

Route Query Parameters

Url appearance: /search?searchText='Madison'

Programmatic Creation

this.history.push({
  pathname: '/search',
  query: {
    searchText: 'Madison'
  }
});

Consumption of the data with in the route

@Component({
  tag: 'search-results'
})
export class SearchResults {
  @Prop() history: RouterHistory;

  render() {
    return (
      <div>{this.history.location.query.searchText}</div>
    );
  }
}

Route State Data

Url appearance: /detail

Programmatic Creation (2 methods listed)

this.history.push('/detail', { docname: docs });
this.history.push({
  pathname: '/detail',
  state: {
    detail_data: docs
  }
);

Consumption of the data with in the route

@Component({
  tag: 'test-demo-three'
})
export class TestDemoThree {
  @Prop() history: RouterHistory;

  render() {
    return (
      <div>{history.location.state}</div>
    );
  }
}