Skip to content

Instantly share code, notes, and snippets.

@thurt
Created April 2, 2020 18:36
Show Gist options
  • Save thurt/dd35b79898e2ea7e90c6ffa9cf30c50e to your computer and use it in GitHub Desktop.
Save thurt/dd35b79898e2ea7e90c6ffa9cf30c50e to your computer and use it in GitHub Desktop.
Manually getting and setting query parameter in a component
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