Last active
April 2, 2020 21:31
-
-
Save thurt/645cf505fce2e7f211d55c7442bbe00b to your computer and use it in GitHub Desktop.
Manually get or set more than one query parameter
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import React, { useEffect, useState } from "react"; | |
import { useLocation, useHistory } from "react-router"; | |
const ExampleQueryParameters = () => { | |
const history = useHistory(); | |
const [state, setState] = useState( | |
Object.fromEntries(new URLSearchParams(useLocation().search)) | |
); | |
useEffect(() => { | |
history.replace( | |
"?" + new URLSearchParams(Object.entries(state)).toString() | |
); | |
}, [state, history]); | |
return ( | |
<> | |
<h2>Example</h2> | |
<button onClick={event => setState({ ...state, q: Date.now() })}> | |
Set "q" param to Date.now() | |
</button> | |
<button | |
onClick={event => setState({ ...state, random: Math.random() })} | |
> | |
Set "random" param to a random number | |
</button> | |
</> | |
); | |
}; | |
export default ExampleQueryParameters; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment