@ericlathrop/react-query-string-router
v0.0.0
Published
Mini router for query string parameters
Downloads
9
Maintainers
Readme
React Query String Router
A mini router for reading/writing query string parameters in your components. Adds new entries to the browser history when parameters are set. Uses React's context and hooks.
Example
Try the demo by running npm start
in the demo
folder.
import React, { useContext } from 'react';
import { QueryStringRouterContext, QueryStringRouterProvider } from "@ericlathrop/react-query-string-router";
function App() {
return (
<QueryStringRouterProvider>
<Counter />
</QueryStringRouterProvider>
);
}
export function Counter() {
const { params, setAllParams } = useContext(QueryStringRouterContext);
const counter = parseInt(params.counter) || 0;
return (
<div>
<div>
Counter is {counter}
</div>
<div>
<button onClick={() => setAllParams({ counter: counter + 1 })}>
Increment counter
</button>
</div>
</div>
);
}
API
QueryStringRouterContext
A normal React Context object.
Use with the useContext
hook like this:
const { params, setAllParams } = useContext(QueryStringRouterContext);
The context contains 2 keys: params
and setAllParams
.
params
The page's query string parameters as a JavaScript object.
setAllParams(newParams)
A function that updates all query string parameters in the URL, and adds a new
entry to the browser history. Exclude a key from newParams
to remove it from
the URL.
QueryStringRouterProvider
A normal React Context.Provider object. Wrap this around the top-level of your app to make the query string parameters available everywhere.