Giter Site home page Giter Site logo

preactjs / preact-router Goto Github PK

View Code? Open in Web Editor NEW
1.0K 14.0 153.0 1.17 MB

:earth_americas: URL router for Preact.

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

License: MIT License

JavaScript 95.95% TypeScript 4.05%
preact router preact-router preact-components

preact-router's People

Contributors

38elements avatar adriantoine avatar alexendoo avatar david-nordvall avatar developit avatar firatsarlar avatar greenkeeperio-bot avatar hikouki avatar jovidecroock avatar lukeed avatar marvinhagemeister avatar marvinschopf avatar matanshavit avatar mbrukman avatar nhubaotruong avatar nicolasparada avatar olpeh avatar pimdewit avatar pmkroeker avatar prateekbh avatar pshev avatar pspeter3 avatar rmacklin avatar robbiewxyz avatar robinvdvleuten avatar rschristian avatar toniopelo avatar valotas avatar vpzomtrrfrt avatar zlondrej avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

preact-router's Issues

Not able to build on Windows

Variable names in the script is preventing build on windows.

> uglifyjs $npm_package_main -cm -o $npm_package_minified_main -p relative --in-source-map ${npm_package_main}.map --source-map ${npm_package_minified_main}.map

fs.js:557
  return binding.open(pathModule._makeLong(path), stringToFlags(flags), mode);
                 ^

Error: ENOENT: no such file or directory, open 'C:\...\Forks\preact-router\${npm_package_main}.map'
    at Object.fs.openSync (fs.js:557:18)
    at Object.fs.readFileSync (fs.js:467:33)
    at Object.<anonymous> (C:\...\Forks\preact-router\node_modules\uglify-js\bin\uglifyjs:285:30)
    at Module._compile (module.js:573:32)
    at Object.Module._extensions..js (module.js:582:10)
    at Module.load (module.js:490:32)
    at tryModuleLoad (module.js:449:12)
    at Function.Module._load (module.js:441:3)
    at Module.runMain (module.js:607:10)
    at run (bootstrap_node.js:382:7)

related: #49

{ Link } not being rendered (2.4.4)

  Windows 10
  Preact: 8.1.0
  Preact-Router: 2.4.4
  Webpack 2.3.3

Edit: This works on preact-router 2.4.3, but not 2.4.4.

The link tags are not getting rendered in the webpage. No errors on build.

<nav>
  <undefined href="/">Home</undefined>
  <undefined href="/profile">Me</undefined>
  <undefined href="/profile/john">John</undefined>
</nav>

I am getting this error on my 8.0 branch of the Preact-Boilerplate found here.

When running tests I get the following error for routing.
undefined is not a constructor (evaluating '(0, _preactRouter.route)('/profile')')

README misleading usage of react-router

Note: preact-router is simple and does not do orchestration for you. If you're looking for more complex solutions like nested routes and view composition, react-router works with preact as long as you alias in preact-compat.

I find the last part of this statement very misleading. It is not the case that react-router must be aliased with preact-compat. I deduced that from the example http://jsfiddle.net/developit/wtpfyfnt. I think it should be rephrased in clearer manner.

Have a great day!

Protected Routes with Preact Router

Hey @developit,

I'm running into some issues trying to implement protected routes. I know react-router has the onEnter prop which helps implement protected routes basically admin pages, etc. How would one implemented this with preact-router.

This is my current approach

// Excerpt from Root Container
render (props) {
  return (
    <Router>
      <Home path='/' user={props.user}/>
      <Contact path='/contact' />
      <ProfileContainer path='/profile' />
      <LoginContainer path='/signin' />
      <PageError type='404' default />
    </Router>
  )
}

Then inside LoginContainer I'm checking if the session is valid, but componentWillMount is not being triggered.

...
componentWillMount () {
  if (isLoggedIn) {
    route('/profile')
  }
}

render (props) {
...

Not sure if this is the right approach. Any pointers will be greatly appreciated. Thanks

Sorting routes by rank

<Router> component now sorts routes by count of path segments or by path string length as a fallback.

Maybe it would helpful allow programmers to specify rank explicitly?

This can be done with new rank attribute for route component. Or with using key attribute as rank.
Or with preserving order of <Router> component children when counts of path segments are equal (stable sort).

How to default to a login form?

I am using browserify to add a series of forms to UI, but I am unable to navigate to the initial Login form. I am using the following and expecting the default Login component to display. Is this the intended function of the example code?

<Router>
  <A path="/" />
  <B path="/b" id="42" />
  <C path="/c/:id" />
  <D default />
</Router>

Below is what I tried:

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

const routes = () =>
    (
        <Router>
          <Login default />
        </Router>
    );

render(
    <routes />, placeholder
);

Programmatical API

I'm working on a Go framework that needs to combine routing in one JSON document that can be read by both JS and Go. To accomplish this, I can't hard-code the routes, I need an API.

Is there an example of programmatical usage of preact-router? Documentation seem to not cover such a case.

Error resolving `preact-router/match`

Following the README, but encountered this error with version 2.5.1:

Module not found: Error: Can't resolve 'preact-router/match' in ...

I'm using webpack 2.4.1. I found preact-router points to ./node_modules/preact-router/dist/preact-router.es.js, in which there is no match or Match.

========
Also, is there a difference between the Link component in preact-router vs. preact-router/match?

(My understanding is that Link inside preact-router/match is Match treated version of the one in preact-router)

Some issue with going to page via link vs just reloading page with url. Via link renders nothing.

Here is the video of behaviour. Keep in mind, when I remove modifiers, behaviour is normal.

https://monosnap.com/file/6XgVsdl9lfhBuSi1gcCL1MMSvggzil

Here you can see that it does not even render anything:

image

It should be strongly related to the case that I'm creating 'Modifiers' for my components, that does modify their behaviour. Their code and idea is shown here: http://www.webpackbin.com/VkXuBY_wb

I tried to recreate errors and empty renders but could not.

TL;DR; about modifiers: in constructor they replace cWM, cWU, render methods with their own, checking and doing something before calling to original methods of instance.

preact-router does some caching of components and cannot find one with modified behaviour?

Also, modifiers have redirects in them also, in my case for Authentication state purpose.

Full hash-routing using preact-router

Let me say first that the current routing implementation works beautifully and I've had no issues, but I have a specific use case where I want to use hashes instead of routes to avoid polluting the javascript history object.

Currently, my main app is setup like this

<Router>
  <Index default />
  <UserContainer path='/users' />
</Router>

This basic implementation gives me 2 routes:
www.example.com -> which loads my Index component
www.example.com/users -> which loads my UserContainer component

The issue I'm seeing is that once I go from / to /users, calling javascript:history.back() will take me back to / since /users is a new route.

I was trying to avoid pushing a new route into my history object, so I thought I could achieve this using hashes for routing instead of full routes.

What I want is
www.example.com -> which loads Index
www.example.com#users -> which loads UserContainer

That way, when i go from / to /users and call javascript:history.back(), it will take me to what I had before i was on / (which is my desired behavior).

Is this possible with preact-router?

Code Splitting Example

Since preact is all about smaller Java Script it would be great if you can provide functionality to support Code Split for preact-router

What are the steps for contributing to this repository?

I tried to use github repo as source for npm package, but I got at the time not really working version without dist. Or I am missing something?

Basically have some things that I already have monkey patches for (redirect loop protection for now).

Route Transitions

How would I transition from one route to another after an action is performed? I have seen transitionTo() being used when a RouterContainer is created, but what is the equivalent in preact? I am also looking at securing a route until someone logs in. I have seen the following for React, is there also an equivalent for the following?

static willTransitionTo(transition, params, query, callback) {
        if (!AuthStore.loggedIn()) {
            // go over to login page
            transition.redirect('/login', null, {
                redirect: transition.path
            });

Star wildcard works only in last "path" segment

It seems that * wildcard works only in the end of path and when it used with some path-parameter.

For example url /post/123/comments matches to route /post/:id*. And matches.id == "123/comments"

But if we use * in the middle of query it does not work:

const App = () => (
  <div class="app">
    <Header />
    <Router>
      <Home path="/*/" />
      <Profile path="/*/profile/:user?" />
      <Error type="404" default />
    </Router>
  </div>
);
const Header = () => (
  <header>
    <nav>
      <a href="/appRoot/">Home</a>
      <a href="/appRoot/profile">Profile</a>
      <a href="/appRoot/profile/john">John</a>
      <a href="/appRoot/asdf">Error</a>
    </nav>
  </header>
);

This config always show "404" page. See JSFiddle

Typescript definition missing important properties or has properties that should be optional.

Causes huge walls of (invalid) errors in our codebase after upgrading to 2.4.0. I've taken to rm'ing index.d.ts for now :)

The issues are:

  • Router has no history prop.
  • RouterArgs.matches should be optional.
  • RouterArgs.url should be optional.
  • RouterArgs.path should be present.

I think that's all, but don't have time atm to try to fix or dig deeper so there may be others.

Support Hashtag Urls

It would be great if you also have a way to have Hashtag urls i.e instead of:

http://developit.github.io/
http://developit.github.io/active
http://developit.github.io/completed

it should be:

http://developit.github.io/#/
http://developit.github.io/#/active
http://developit.github.io/#/completed

I mean currently we have some companies where we develop some apps and their browsers won't work nicely with these native urls.

Ignore an specific router [question]

I have the follow configuration:

<Router onChange={ onChange }>
	<Home path="/" />
	<Blog path="/blog" />
	<Article path="/blog/:title" />
	<Credit path="/credit" />
	<Error404 default />
</Router>

but it cach the route /assets
How can ignore this route?

NPM distribution for 1.2.0 not pulling in utils.js

The new package in npm doesn't appear to have properly bundled in the newly factored out utils.js class. I get this when trying to use the new 1.2.0 package in my project

ERROR in ./~/preact-router/dist/preact-router.js
Module not found: Error: Cannot resolve 'file' or 'directory' ./util in /Users/bneff/repos/push-notification-pub-tool/node_modules/preact-router/dist
 @ ./~/preact-router/dist/preact-router.js 1:73-118

Props of Router component children are being erased

Right now I'm running into a strange situation where the Router component will erase props on child components. For example, I have a Slides component that is the only child of Router:

render(){
  return (
    <Router>
      <Slides path="/:slide?" slide="1" default />
    </Router>
  );
}

Inside of the slide component, this.props.slide is always an empty string, no matter what I set it to. If I remove the Router component around the Slides component, this.props.slide populates properly.

Some pertinent version info:
preact 8.1.0
preact-router 2.5.2
webpack 2.4.1

Currently using the babel-plugin-transform-react-jsx plugin to parse JSX. Are there any reasons why this would occur? I feel like it's a bug.

Thanks!

does it support Dynamic routing?

i try that but it is not working.
import { h, Component } from 'preact';
import { BrowserRouter } from 'react-router-dom';
import { Route } from 'react-router';
const Containers = () => (
    <div className="containers">Containers</div>
)
export default class App extends Component {
    constructor(props) {
        super(props);
        this.state = {
            RouteComponent: Containers
        }
    }
    shouldComponentUpdate(nextProps, nextState) {
        const { RouteComponent: lastRouteComponent } = this.state;
        const { RouteComponent: nextRouteComponent } = nextState;
        if (!lastRouteComponent && nextRouteComponent) {
            return true;
        }
        return false;
    }
    componentWillMount() {
        const name = location.pathname
        const first = name.substring(0, 1).toUpperCase();
        const end = name.substring(1, name.length);
        const pages = first + end;
        import ("." + pages + '/index')
        .then(RouteComponent => this.setState({ RouteComponent }))
            .catch(err => console.log('Failed to load Component', err))
    }
    render() {
        const { RouteComponent } = this.state;
        return (
            <BrowserRouter>
                    <Route
                    path="/"
                    component={ RouteComponent }
                    exact />
            </BrowserRouter>
        );
    }
}


How to make a async router?

Just like react-router, How to make a dynamic router?

This is react-router:

const CourseRoute = {
  path: 'course/:courseId',

  getChildRoutes(location, callback) {
    require.ensure([], function (require) {
      callback(null, [
        require('./routes/Announcements'),
        require('./routes/Assignments'),
        require('./routes/Grades'),
      ])
    })
  },

  getIndexRoute(location, callback) {
    require.ensure([], function (require) {
      callback(null, {
        component: require('./components/Index'),
      })
    })
  },

  getComponents(location, callback) {
    require.ensure([], function (require) {
      callback(null, require('./components/Course'))
    })
  }
}

so...Does preat-router have getCompoents? or other?

After preact project build,router failed.

I use react-router as I cloned preact-boilerplate and develop with all it's dependencies .After my development I release it with npm run build and I get html/style/bundle files.Then I host them with nginx and give it a server name preact.demo.com,I can access http://preat.demo.com but I cant access preact.demo.com/route-one while I can view it(http://localhost:PORT/route-one) when the webpack develop server is on.Any usage mistacks?

Is there a way to enumerate rendered componets?

I need it on server-side to collect critical css.
react-router could do it passing renderProps.components - so I can iterate over components and ask about css resources.

Could it be achieved in preact?

Preact-router 2.4.2 fails to parse with webpack 2.3.2 and node 6.10.1

Our app stopped building roughly around when 2.4.2 was tagged. Our dependencies looked like this:

  "dependencies": {
    "preact": "^7.2.1",
    "preact-compat": "^3.14.3",
    "preact-router": "^2.4.1"
  }

Webpack failed with this message:

Module parse failed: /home/joe/code/github/my-project/node_modules/preact-router/src/index.js Unexpected token (253:28)
You may need an appropriate loader to handle this file type.
| }
| 
| const Route = ({ component, ...props }) => {
|       return h(component, props);
| };

Locking in 2.4.1 fixed the issue. Any ideas?

Nested Routes

Sorry, I'm very new to react and haven't been able to get nested routes working. Could you possibly tell me what I'm doing wrong. I forked your real world example.

I can't seem to load the child view.

https://jsfiddle.net/uwd4x6xx/1/

Path priority issue

In below routes, the url /about will navigate to <Mail path="/:id"/> instead of <About path="/about" />

Slack Discussion

<Router> 
  <Inbox path="/" default />              
  <About path="/about" />               
  <Mail path="/:id"/>            
</Router>

I am trying out fixes as per this comment But as of now no luck. Will update here is If I made any progress.

Before further work

A common pattern I've noticed around JSX routers is to use <Router>, <Route> , <Link> .

I wanted to ask: Isn't <Link> enough?

Unmounting and mounting entire page components via path="" or <Route> has 2 drawbacks:

  1. What if my <About> page and my <TermsOfService> page only differ by <Title> and <PageText>? Why do I swap the entire page? Especially if my <Title> and <PageText> are not sibling elements and have different parents. One is in the header, the other is in the main body section. Both pages migh also share other common elements like in-page sidebar. Additionally swapping entire page removes the ability to only animate the changed elements, not the entire page.
  2. Routing casues a DOM mutation that is triggered not by store/redux state change (via action) but custom logic (<Route>).

Is it crazy to propose just a single element <Link> that has a onPageNavigation contextType property which in decide what to do when page changes. If someone uses redux, they will set onPageNavigation to execute a PAGE_NAVIGATION_STARTED action, possibly supplying route name if named.

Error after upgrading to Preact 8

After updating Preact to 8.1.0 (I was on 6!), I'm seeing this error:

preact-router.es.js?b6d5:58 Uncaught TypeError: Cannot read property 'attributes' of null
    at pathRankSort (eval at <anonymous> (http://localhost:3000/bundle.js:148:1), <anonymous>:67:12)
    at Array.sort (native)
    at Router.getMatchingChildren (eval at <anonymous> (http://localhost:3000/bundle.js:148:1), <anonymous>:304:27)
    at Router.render (eval at <anonymous> (http://localhost:3000/bundle.js:148:1), <anonymous>:325:21)
    at renderComponent (eval at <anonymous> (http://localhost:3000/bundle.js:73:1), <anonymous>:263:38)
    at renderComponent (eval at <anonymous> (http://localhost:3000/bundle.js:73:1), <anonymous>:275:25)
    at renderComponent (eval at <anonymous> (http://localhost:3000/bundle.js:73:1), <anonymous>:275:25)
    at renderComponent (eval at <anonymous> (http://localhost:3000/bundle.js:73:1), <anonymous>:275:25)
    at setComponentProps (eval at <anonymous> (http://localhost:3000/bundle.js:73:1), <anonymous>:244:103)
    at buildComponentFromVNode (eval at <anonymous> (http://localhost:3000/bundle.js:73:1), <anonymous>:331:13)
pathRankSort @ preact-router.es.js?b6d5:58
getMatchingChildren @ preact-router.es.js?b6d5:295
render @ preact-router.es.js?b6d5:316
renderComponent @ VM2730:263
renderComponent @ VM2730:275
renderComponent @ VM2730:275
renderComponent @ VM2730:275
setComponentProps @ VM2730:244
buildComponentFromVNode @ VM2730:331
idiff @ VM2730:134
diff @ VM2730:110
render @ VM2730:363
(anonymous) @ index.jsx?a49b:25
(anonymous) @ bundle.js:873
__webpack_require__ @ bundle.js:20
(anonymous) @ bundle.js:66
(anonymous) @ bundle.js:69

I'm using version 2.5.1 of preact-router. Has anyone seen this issue before?

Thanks!

Unused Link/handleLinkClick?

The readme says that a tags are automatically wired.
How is that supposed to happen? Through the exported Link which should be manually used by the user in place of the a tag?
I can't find any other place where the automatic wiring is happening.

The exported Link is also not being used in the real example: http://jsfiddle.net/developit/qc73v9va/
handleLinkClick is never called

If that's the case, I'd suggest to just update documentation accordingly or remove the Link export

Navigating to a route with a query parameter and then to the same route without a query parameter will pass the old value of the query parameter in the component props

Iā€™m noticing that if I route to a path with a query parameter, e.g. /profile?query_param=1 inside the render method, props.query_param is "1", as expected. However, if I subsequently route to /profile with no query param, props.query_param is still "1" when Iā€™d expect it to be undefined. This seems like a bug.

Below is a small patch on top of https://github.com/developit/preact-boilerplate/tree/65fd23960c8efa323bc276b799394b578d1ce70d that demonstrates this issue:

Patch

Index: src/components/profile/index.js
IDEA additional info:
Subsystem: com.intellij.openapi.diff.impl.patch.CharsetEP
<+>UTF-8
===================================================================
--- src/components/profile/index.js	(revision 65fd23960c8efa323bc276b799394b578d1ce70d)
+++ src/components/profile/index.js	(revision )
@@ -9,17 +9,17 @@
 	// gets called when this route is navigated to
 	componentDidMount() {
 		// start a timer for the clock:
-		this.timer = setInterval(::this.updateTime, 1000);
-		this.updateTime();
+		//this.timer = setInterval(::this.updateTime, 1000);
+		//this.updateTime();
 
 		// every time we get remounted, increment a counter:
 		this.setState({ count: this.state.count+1 });
 	}
 
 	// gets called just before navigating away from the route
-	componentWillUnmount() {
-		clearInterval(this.timer);
-	}
+	//componentWillUnmount() {
+	//	clearInterval(this.timer);
+	//}
 
 	// update the current time
 	updateTime() {
@@ -28,7 +28,8 @@
 	}
 
 	// Note: `user` comes from the URL, courtesy of our router
-	render({ user }, { time, count }) {
+	render({ user, query_param }, { time, count }) {
+		console.log(query_param);
 		return (
 			<div class={style.profile}>
 				<h1>Profile: { user }</h1>
@@ -36,6 +37,8 @@
 
 				<div>Current time: { time }</div>
 				<div>Profile route mounted { count } times.</div>
+				<p><a href={`${window.location.pathname}?query_param=1`}>query_param=1</a></p>
+				<p><a href={window.location.pathname}>no query_param</a></p>
 			</div>
 		);
 	}

Feature: Active class when Link href matches window.location

I'm currently building a navigation with preact-router but I'm stuck with setting an active css class when the url matches the href prop. The <Link>-component doesn't support some sort of active class.

Of course I could switch back to react-router, but it seems kinda overkill for my purpose.

[Feature Request] ES6 Build

I noticed that preact-router exposes jsnext:main but it isn't quite ES6. There you have JSX syntax and object rest destructuring in function params, example:

const Link = ({ children, ...props }) => (
  <a {...props} onClick={handleLinkClick}>{ children }</a>
);

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.