react-router-state
v1.0.15
Published
React state api which append value to quey params
Downloads
5
Maintainers
Readme
react-router-state
Preview
Open this example on StackBlitz:
Installation
Using npm:
npm install react-router-state
Or using yarn:
yarn add react-router-state
API
const [value, setValue] = useQueryState(key, defaultValue)
| Name | Type | Description | | :----------: | :------------------------------------------: | :----------------------------: | | defaultValue | string | default state value | | key | string | param key to append to the url | | value | string | current value | | setValue | React.Dispatch<React.SetStateAction> | set state value |
Example
import { useQueryState } from 'react-router-state';
export default function () => {
const [value, setValue] = useQueryState("name", "john");
return (
<div>
<h1>Name query param: ${value}</h1>
<button onClick={() => setValue("amin")} >
click to change name query parameter
</button>
</div>
)
}
Use cases
There are some cases that you want to have a persistance state when you share a url of you web application to someone else. For example you click on a button which opens a modal and you want to share the link and the modal should be open once the app is loaded. use can do something like this example:
const [isOpen, setIsOpen] = useQueryState("isModalOpen", "false");
return (
<div>
<button onClick={() => setIsOpen("true")}>click to open modal</button>
<Modal isOpen={isOpen} onClose={() => setIsOpen("false")} />
</div>
);