Type Route

Type Route

  • Docs
  • GitHub
  • v0.6.0

›Guides

Introduction

  • Getting Started
  • Simple React Example

Guides

  • Code Splitting
  • Complex Route Parameters
  • Custom Link Behavior
  • Custom Query String
  • Data Fetching
  • Nested and Similar Routes
  • No Match (404)
  • Page Layout
  • Preventing Navigation
  • Programmatic Navigation
  • Redirects
  • Rendering Links
  • Route Parameters
  • Scroll Restoration
  • Server Side Rendering
  • Styling of Links for the Currently Active Route
  • Type Route without React
  • Wildcard Routes
  • Previous Release Docs
  • Guide Missing?

API Reference

    <ParameterDefinition>

    • param

    <RouteDefinition>

    • defineRoute
    • extend

    <RouteGroup>

    • createGroup
    • has

    <Route>

    • action
    • href
    • link
    • name
    • params
    • push
    • replace

    <Router>

    • createRouter
    • useRoute
    • RouteProvider
    • routes
    • session

    Types

    • Link
    • QueryStringSerializer
    • Route
    • RouterOpts
    • SessionOpts
    • ValueSerializer

    Miscellaneous

    • noMatch
    • preventDefaultLinkClickBehavior
Edit

Rendering Links

Links in single page applications are unique for the fact that they do not trigger a page load. Typically all a link would require is an href property:

<a href="/foo/bar">FooBar</a>

This works as expected but causes the entire page to reload whenever the link is clicked. If we're building a single page application we'd like to avoid that. To do so we need to capture link clicks and prevent the default behavior.

<a
  href="/foo/bar"
  onClick={event => {
    event.preventDefault();
    // Then trigger some state update so we know we're at "/foo/bar"
  }}
>
  Foo Bar
</a>

Using Type Route the above would look something like this:

<a
  href={routes.fooBar().href}
  onClick={event => {
    event.preventDefault();
    routes.fooBar().push();
  }}
>
  Foo Bar
</a>

This pattern becomes especially repetitive when the route has parameters. What's more simply calling preventDefault on the event is not sufficient (see preventDefaultLinkClickBehavior). To solve this problem in a framework agnostic way Type Route has the link property on routes.

<a {...routes.fooBar().link}>Foo Bar</a>

The link property is an object with href and onClick properties. Destructure these into the props of the <a> tag and you achieve the same functionality as above in a less verbose way. Its important to provide both the href and onClick properties to the link. onClick will ensure we don't trigger a page reload when clicking the link and href will ensure the browser still treats the link as a link.

Related Pages

  • Custom Link Behavior
  • Styling of Links for the Currently Active Route
  • preventDefaultLinkClickBehavior
← RedirectsRoute Parameters →
Type Route is a Type Hero project  ·  Copyright © 2020