preactjs / preact-router Goto Github PK
View Code? Open in Web Editor NEW:earth_americas: URL router for Preact.
Home Page: http://npm.im/preact-router
License: MIT License
:earth_americas: URL router for Preact.
Home Page: http://npm.im/preact-router
License: MIT License
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
Hi, first of all thanks for Preact and its tooling, it's really great. š
I'm looking to add preact-transition-group
to my routing so that each component can handle componentWillEnter
, componentWillAppear
and componentWillLeave
.
So far I haven't found a clean way of integrating these two together without patching this module.
Experience-Monks@966d4f2#diff-1fdf421c05c1140f6d71444ea2b27638L248
Is there another way this might be possible?
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')')
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!
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
Hi developit , I think it should support relative path, č°¢č°¢ ^ ^
<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).
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
);
I was wondering if onEnter and onLeave hooks are already supported in preact-router. If not, is it something on a roadmap?
https://registry.npmjs.org/preact-router/-/preact-router-2.3.2.tgz
There's also a preact-scroll-viewport
directory in there, doesn't look like it's used
is this same to react router ?
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.
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
)
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:
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.
In react-router
, the target to the Link
is through the to
prop:
https://github.com/ReactTraining/react-router/blob/master/modules/Link.js#L51
But in preact-router
, props are sent directly to a
tag, requiring the href
prop to the component:
https://github.com/developit/preact-router/blob/master/src/index.js#L146
Isn't better allow to use the to
prop?
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?
Since preact is all about smaller Java Script it would be great if you can provide functionality to support Code Split for preact-router
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).
react-router hashHistory
example.com/#/some/path
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
});
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
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.
Is there a way to have a handler/callback on navigation events of <Router/>
? Maybe something similar to this: http://strml.viewdocs.io/react-router-component/#user-content-navigation-callbacks
I saw in the code that <Router/>
has a prop
named onChange
(here: https://github.com/developit/preact-router/blob/master/src/index.js#L164), but it does not seem to be used anywhere in the component other than shouldComponentUpdate
hey, I was just giving this a try and doing the standard comparison with react and couldn't get the hashHistory (#60) to work.
You can see the code I've used here : peter-mouland/react-lego@master...preact
Any idea what i'm missing?
ps, love how simple it was to do the swap from React!
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.
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?
If link are added with somethings like innerHTML or dangerouslySetInnerHTML , the links are not working because of isPreactElement(t)
(and that makes sense).
https://github.com/developit/preact-router/blob/master/src/index.js#L117
I use dangerouslySetInnerHTML
for translated content which can use <a>
inside.
How should I handle these links ?
Thanks ! :)
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
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!
Hi,
when I deploy a preact bundle to my web-server anythink works fine as long as I start at the root.
eg: www.mydomain/
But if I navigate to a subpath like this:
www.mydomain/profile
I get a 404 ?
How to solve this, please ?
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>
);
}
}
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?
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?
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?
As question told.
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?
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.
In below routes, the url /about
will navigate to <Mail path="/:id"/>
instead of <About path="/about" />
<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.
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:
<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.<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.
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!
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
the demo does not open with preact@beta version. it works with [email protected] . this.linkState is not working.
Was working on creating tests to exercise the TypeScript definitions and ran across this error with the definition for Router
:
Identifier expected: 'static' is a reserved word in strict mode. Modules are automatically in strict mode.
https://github.com/developit/preact-router/blob/master/src/index.d.ts#L14
Simplest case:
<Router static={true}>
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:
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>
);
}
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.
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>
);
This is part of the code that uses ::route from Router:
Main render occurs and then in 1 second ::route used to route back to index (in my case when user is not authenticated), but when clicking back and back something bad happens when everything becomes broken and empty:
Thanks for this easy to use Router. But I think we should have the router also accept index pages. What do you think?
A declarative, efficient, and flexible JavaScript library for building user interfaces.
š Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.
TypeScript is a superset of JavaScript that compiles to clean JavaScript output.
An Open Source Machine Learning Framework for Everyone
The Web framework for perfectionists with deadlines.
A PHP framework for web artisans
Bring data to life with SVG, Canvas and HTML. ššš
JavaScript (JS) is a lightweight interpreted programming language with first-class functions.
Some thing interesting about web. New door for the world.
A server is a program made to process requests and deliver data to clients.
Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.
Some thing interesting about visualization, use data art
Some thing interesting about game, make everyone happy.
We are working to build community through open source technology. NB: members must have two-factor auth.
Open source projects and samples from Microsoft.
Google ā¤ļø Open Source for everyone.
Alibaba Open Source for everyone
Data-Driven Documents codes.
China tencent open source team.