Created
April 2, 2020 18:36
-
-
Save thurt/dd35b79898e2ea7e90c6ffa9cf30c50e to your computer and use it in GitHub Desktop.
Manually getting and setting query parameter in a component
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 { useHistory, useLocation } from "react-router"; | |
const ExampleQueryParam = () => { | |
const history = useHistory(); | |
const location = useLocation(); | |
const [q, setQ] = useState(new URLSearchParams(location.search).get("q")); | |
useEffect(() => { | |
history.replace("?" + new URLSearchParams([["q", q]]).toString()); | |
}, [q, history]); | |
return ( | |
<> | |
<h1>Example</h1> | |
<button onClick={event => setQ(Date.now().toString())}> | |
Set "q" param to Date.now() | |
</button> | |
</> | |
); | |
}; | |
export default ExampleQueryParam; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment