Coder Social home page Coder Social logo

amiller-gh / preact-router Goto Github PK

View Code? Open in Web Editor NEW

This project forked from preactjs/preact-router

0.0 1.0 0.0 725 KB

:earth_americas: URL router for Preact.

Home Page: http://npm.im/preact-router

License: MIT License

JavaScript 95.03% TypeScript 4.97%

preact-router's Introduction

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. React Router 4 even works directly with Preact, no compatibility layer needed!

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. You can even mix-and-match URL parameters and normal props. You can also make params optional by adding a ? to it.

<Router>
  <A path="/" />
  <B path="/b" id="42" />
  <C path="/c/:id" />
  <C path="/d/:optional?/:params?" />
  <D 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

Its 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

License

MIT

preact-router's People

Contributors

38elements avatar adriantoine avatar alexendoo avatar andrewiggins avatar andybons avatar ashsearle avatar aweary avatar bnolan avatar cmaster11 avatar davetherave2010 avatar david-nordvall avatar davideast avatar developit avatar greenkeeperio-bot avatar hassanbazzi avatar hikouki avatar hiteshjoshi avatar jovidecroock avatar k1r0s avatar lionralfs avatar lukeed avatar lukvonstrom avatar marvinhagemeister avatar pmkroeker avatar prateekbh avatar rmacklin avatar scurker avatar sync avatar valotas avatar webyom avatar

Watchers

 avatar

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    ๐Ÿ–– Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. ๐Ÿ“Š๐Ÿ“ˆ๐ŸŽ‰

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google โค๏ธ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.