unurl
v0.10.0
Published
Simple reactive URL-like object
Downloads
28
Readme
unurl
Simple reactive URL object
Note: uses Proxy, check browser support before using.
Install
npm i unurlUsage
const { url, onChange } = require('unurl')
onChange(() => {
// Fires when url changes
})
function changeURL() {
url.pathname = '/new-path'
url.searchParams.append('foo', 'bar')
}const { url } = require('unurl')
const { connect } = require('unurl/react')
const ReactComponentConnectStyle = connect(() => {
// re-renders when url changes
})const { useUrl } = require('unurl/react')
const ReactComponentEffectStyle = () => {
const url = useUrl()
// re-renders when url changes
}API
const { url, searchParams, onChange, listen } = require('unurl')url
A Proxy of new URL that fires onChange whenever a property is changed.
@property {string} hostnameA String containing the domain of the URL.@property {string} pathnameA String containing an initial '/' followed by the path of the URL.- ...URL#Properties
searchParams
searchParams but in an object-form with values parsed for easier consumption.
Querystring | Object | Remark
-------------|-------------------|----------------
?a=b | { a: 'b' } | key=value converted to { key: value }
?a=1 | { a: 1 } | JSON parsed (~~'1'~~ 1)
?a, ?a= | { a: true } | Existence of key inferred as value true
?a=1,b | { a: [1, 'b'] } | Comma-separated parsed as array
onChange
A function to register a callback that's fired whenever url is changed, or when listening to browser events.
@param {function} callbackCallback to fire when url changes@returns {function} unRegisterFrees thecallbackfrom firing anymore
listen
Listen to browser events: click (on an <a> element), popstate, and hashchange to fire onChange.
@param {object} [opts]@param {Boolean|Object} [opts.click={}]Listen to click events on all <a> elements. Will prevent ifhrefis from the same (current) hostname. Options will be passed to addEventListener.@returns {function} removeListenerRemoves and frees the attached event listeners
React API
React-specific helper functions.
const { connect, useUrl } = require('unurl/react')connect
Converts a React Component into one that re-renders whenever url changes.
@param {ReactComponent|Function} componentReact Component or a function to wrap@returns {ReactComponent} componentWrapper Component that renders the abovecomponent
