Skip to content

Create a redirect

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

There are a few different approaches to creating a redirect using the stencil-router. We will cover these and try to identify which fits best for your use case.

Reacting to application state

The following example shows a declarative redirect using stencil-route-redirect. Most likely you would use this if there is an application or component state that would require a redirect.

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

  render() {
    if (!hasSeenInterstitial) {
      <stencil-route-redirect url="/promo" />
    }
    return (
      <div>Welcome to App Corp</div>
    );
  }
}

Responding to a user action

The following example shows the use of a redirect using the router history api. This is useful if you want to react to a user action. In this case we are redirecting to a user detail page on a successful login.

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

  async handleSubmit = (e) => {
    e.preventDefault();

    const isSuccessFul = await login();
    if (isSuccessFul) {
      this.history.replace('/user');
    } else {
      // Error logic
    }
  }

  render() {
    return (
      <form onSubmit={(e) => this.handleSubmit(e)}>
        <label>
          Username:
          <input type="text"/>
        </label>
        <label>
          Password:
          <input type="password"/>
        </label>
        <input type="submit" value="Submit" />
      </form>
    );
  }
}