with-url-state
Lifts the state out of a react component and into the url
Installation
To install with npm:
npm install with-url-state --save
To install with yarn:
yarn add with-url-state
Usage
Check out the the demo or view the code
The api is very similar to useState
with some important differences:
- Url state must be an object, you can't use any primitive values likes strings, booleans, numbers or collections such as Map or Set.
- Url values in your state object must be strings as there is no way to tell the if
?someParam=false
should be deserialized to a boolean or to a string. - The url is shared between your whole app. Multiple components using
useUrlState
will all affect the url simultaneously. This means that asetUrlState
call will cause all components usinguseUrlState
to re-render. - State is shallow merged into the previous state e.g.
This allows components to adjust the url without having to worry about 'destroying' state that other components may be relying on.newState = { ...previousState, ...stateUpdate, }
- The url is easily edited by your users, you should validate the values you receive
Example
const UrlForm = { const urlState setUrlState = return <div className="UrlForm"> <div className="current-state" style= backgroundColor: propsurlStatecolor > <div>urlStatecolor</div> </div> <div className="color-buttons"> <button className="Red" onClick= > Red </button> <button className="Green" onClick= > Green </button> <button className="Blue" onClick= > Blue </button> </div> </div> }
Recipes
Higher-order component
If your application relies on the removed higher-order component API you can re-implement it like so:
let { let urlState setUrlState = return <WrappedComponent ...props urlState=urlState setUrlState=setUrlState />}
Render-prop
If your application relies on the removed render prop API you can re-implement it like so:
const UrlState = { let urlState setUrlState = return }
Motivation
with-url-state
automates tiresome query parameter manipulations, simplifying components where the URL will be used for sharing, search results, querying data or tracking a visible portion of a map.
The api provided is:
- based on hooks
- type-safe thanks to Typescript
- very similar to Reacts built in state apis, so converting a component which already manages state is usually as simple as replacing
useState
withuseUrlState
!
Pollyfill
For use in IE11 you will need https://github.com/kumarharsh/custom-event-polyfill and add the following to the entry point of your application:
;if typeof Event !== 'function' windowEvent = CustomEvent; ``