All Projects β†’ preactjs β†’ Preact Router

preactjs / Preact Router

Licence: mit
🌎 URL router for Preact.

Programming Languages

javascript
184084 projects - #8 most used programming language

Projects that are alternatives of or similar to Preact Router

Wouter
πŸ₯’ A minimalist-friendly ~1.5KB routing for React and Preact. Nothing else but HOOKS.
Stars: ✭ 3,654 (+373.93%)
Mutual labels:  router, preact
Hydux
A light-weight type-safe Elm-like alternative for Redux ecosystem, inspired by hyperapp and Elmish
Stars: ✭ 216 (-71.98%)
Mutual labels:  router, preact
Vhtml
Render JSX/Hyperscript to HTML strings, without VDOM 🌈
Stars: ✭ 556 (-27.89%)
Mutual labels:  preact
Found
Extensible route-based routing for React applications
Stars: ✭ 718 (-6.87%)
Mutual labels:  router
Micro Router
πŸš‰ A tiny and functional router for Zeit's Micro
Stars: ✭ 621 (-19.46%)
Mutual labels:  router
React Router Relay
[Deprecated] Relay Classic integration for React Router
Stars: ✭ 561 (-27.24%)
Mutual labels:  router
Microsite
Do more with less JavaScript. Microsite is a smarter, performance-obsessed static site generator powered by Preact and Snowpack.
Stars: ✭ 632 (-18.03%)
Mutual labels:  preact
Gear
A lightweight, composable and high performance web service framework for Go.
Stars: ✭ 544 (-29.44%)
Mutual labels:  router
Lion
Lion is a fast HTTP router for building modern scalable modular REST APIs in Go
Stars: ✭ 750 (-2.72%)
Mutual labels:  router
Nerv
A blazing fast React alternative, compatible with IE8 and React 16.
Stars: ✭ 5,409 (+601.56%)
Mutual labels:  preact
Flutter thrio
flutter_thrio makes it easy and fast to add flutter to existing mobile applications, and provide a simple and consistent navigator APIs.
Stars: ✭ 717 (-7%)
Mutual labels:  router
Nwb
A toolkit for React, Preact, Inferno & vanilla JS apps, React libraries and other npm modules for the web, with no configuration (until you need it)
Stars: ✭ 5,429 (+604.15%)
Mutual labels:  preact
Ciscoconfparse
Parse, Audit, Query, Build, and Modify Cisco IOS-style configurations. Python Infrastructure as Code (IaC) for Cisco IOS (and other vendors).
Stars: ✭ 562 (-27.11%)
Mutual labels:  router
Mouthful
Mouthful is a self-hosted alternative to Disqus
Stars: ✭ 681 (-11.67%)
Mutual labels:  preact
50weekly
50weekly ε‘ηŽ°ι«˜θ΄¨ι‡ηš„ε‰η«―θ΅„ζΊ 第三十六周已更新
Stars: ✭ 560 (-27.37%)
Mutual labels:  preact
Androuter
A android router framework used to map url to activities or actions.
Stars: ✭ 730 (-5.32%)
Mutual labels:  router
Awesome Preact
A curated list of amazingly awesome things regarding Preact ecosystem 🌟
Stars: ✭ 546 (-29.18%)
Mutual labels:  preact
Gitalk
Gitalk is a modern comment component based on Github Issue and Preact.
Stars: ✭ 5,778 (+649.42%)
Mutual labels:  preact
Navaid
A navigation aid (aka, router) for the browser in 850 bytes~!
Stars: ✭ 648 (-15.95%)
Mutual labels:  router
Path To Regexp
Turn a path string such as `/user/:name` into a regular expression
Stars: ✭ 6,789 (+780.54%)
Mutual labels:  router

preact-router

NPM travis-ci

Connect your Preact components up to that address bar.

preact-router provides a <Router /> component that conditionally renders its children when the URL matches their path. It also automatically wires up <a /> elements to the router.

πŸ’ Note: This is not a preact-compatible version of React Router. preact-router is a simple URL wiring and does no orchestration for you.

If you're looking for more complex solutions like nested routes and view composition, react-router works great with preact as long as you alias in preact/compat.

See a Real-world Example ➑️


Usage Example

import Router from 'preact-router';
import { h, render } from 'preact';
/** @jsx h */

const Main = () => (
	<Router>
		<Home path="/" />
		<About path="/about" />
		// Advanced is an optional query
		<Search path="/search/:query/:advanced?" />
	</Router>
);

render(<Main />, document.body);

If there is an error rendering the destination route, a 404 will be displayed.

Handling URLS

πŸ’ Pages are just regular components that get mounted when you navigate to a certain URL. Any URL parameters get passed to the component as props.

Defining what component(s) to load for a given URL is easy and declarative. Querystring and :parameter values are passed to the matched component as props. Parameters can be made optional by adding a ?, or turned into a wildcard match by adding * (zero or more characters) or + (one or more characters):

<Router>
  <A path="/" />
  <B path="/b" id="42" />
  <C path="/c/:id" />
  <C path="/d/:optional?/:params?" />
  <D path="/e/:remaining_path*" />
  <E path="/f/:remaining_path+" />
  <F default />
</Router>

Lazy Loading

Lazy loading (code splitting) with preact-router can be implemented easily using the AsyncRoute module:

import AsyncRoute from 'preact-async-route';
<Router>
  <Home path="/" />
  <AsyncRoute
    path="/friends"
    getComponent={ () => import('./friends').then(module => module.default) }
  />
  <AsyncRoute
    path="/friends/:id"
    getComponent={ () => import('./friend').then(module => module.default) }
    loading={ () => <div>loading...</div> }
  />
</Router>

Active Matching & Links

preact-router includes an add-on module called match that lets you wire your components up to Router changes.

Here's a demo of <Match>, which invokes the function you pass it (as its only child) in response to any routing:

import Router from 'preact-router';
import Match from 'preact-router/match';

render(
  <div>
    <Match path="/">
      { ({ matches, path, url }) => (
        <pre>{url}</pre>
      ) }
    </Match>
    <Router>
      <div default>demo fallback route</div>
    </Router>
  </div>
)

// another example: render only if at a given URL:

render(
  <div>
    <Match path="/">
      { ({ matches }) => matches && (
        <h1>You are Home!</h1>
      ) }
    </Match>
    <Router />
  </div>
)

<Link> is just a normal link, but it automatically adds and removes an "active" classname to itself based on whether it matches the current URL.

import { Router } from 'preact-router';
import { Link } from 'preact-router/match';

render(
  <div>
    <nav>
      <Link activeClassName="active" href="/">Home</Link>
      <Link activeClassName="active" href="/foo">Foo</Link>
      <Link activeClassName="active" href="/bar">Bar</Link>
    </nav>
    <Router>
      <div default>
        this is a demo route that always matches
      </div>
    </Router>
  </div>
)

Default Link Behavior

Sometimes it's necessary to bypass preact-router's link handling and let the browser perform routing on its own.

This can be accomplished by adding a native boolean attribute to any link:

<a href="/foo" native>Foo</a>

Detecting Route Changes

The Router notifies you when a change event occurs for a route with the onChange callback:

import { render, Component } from 'preact';
import { Router, route } from 'preact-router';

class App extends Component {

  // some method that returns a promise
  isAuthenticated() { }

  handleRoute = async e => {
    switch (e.url) {
      case '/profile':
        const isAuthed = await this.isAuthenticated();
        if (!isAuthed) route('/', true);
        break;
    }
  };

  render() {
    return (
      <Router onChange={this.handleRoute}>
        <Home path="/" />
        <Profile path="/profile" />
      </Router>
    );
  }

}

Redirects

Can easily be implemented with a custom Redirect component;

import { Component } from 'preact';
import { route } from 'preact-router';

export default class Redirect extends Component {
  componentWillMount() {
    route(this.props.to, true);
  }

  render() {
    return null;
  }
}

Now to create a redirect within your application, you can add this Redirect component to your router;

<Router>
  <Bar path="/bar" />
  <Redirect path="/foo" to="/bar" />
</Router>

Custom History

It's possible to use alternative history bindings, like /#!/hash-history:

import { h } from 'preact';
import Router from 'preact-router';
import { createHashHistory } from 'history';

const Main = () => (
    <Router history={createHashHistory()}>
        <Home path="/" />
        <About path="/about" />
        <Search path="/search/:query" />
    </Router>
);

render(<Main />, document.body);

Programmatically Triggering Route

It's possible to programmatically trigger a route to a page (like window.location = '/page-2')

import { route } from 'preact-router';

route('/page-2')  // appends a history entry

route('/page-3', true)  // replaces the current history entry

Nested Routers

The <Router> is a self-contained component that renders based on the page URL. When nested a Router inside of another Router, the inner Router does not share or observe the outer's URL or matches. Instead, inner routes must include the full path to be matched against the page's URL:

import { h, render } from 'preact';
import Router from 'preact-router';

function Profile(props) {
    // `props.rest` is the rest of the URL after "/profile/"
    return (
      <div>
        <h1>Profile</h1>
        <Router>
          <MyProfile path="/profile/me" />
          <UserProfile path="/profile/:user" />
        </Router>
      </div>
    );
}
const MyProfile = () => (<h2>My Profile</h2>);
const UserProfile = (props) => (<h2>{props.user}</h2>);

function App() {
  return (
    <div>
      <Router>
        <Home path="/" />
        <Profile path="/profile/:rest*" />
      </Router>
      <nav>
        <a href="/">Home</a>
        <a href="/profile/me">My Profile</a>
        <a href="/profile/alice">Alice's Profile</a>
      </nav>
    </div>
  );
}

render(<App />, document.body);

License

MIT

Note that the project description data, including the texts, logos, images, and/or trademarks, for each open source project belongs to its rightful owner. If you wish to add or remove any projects, please contact us at [email protected].