forked from sergiodxa/remix-utils
-
Notifications
You must be signed in to change notification settings - Fork 0
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
Add ExistingSearchParams util (sergiodxa#279)
Adds `ExistingSearchParams` from https://www.jacobparis.com/content/existing-params I'll update my article once this is published Let me know if I've missed any steps here
- Loading branch information
1 parent
5c61c3c
commit 88e9159
Showing
3 changed files
with
100 additions
and
0 deletions.
There are no files selected for viewing
This file contains 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
This file contains 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
This file contains 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
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,56 @@ | ||
import * as React from "react"; | ||
import { useSearchParams } from "@remix-run/react"; | ||
|
||
type Props = { | ||
/** | ||
* These query params will not be included as hidden inputs. | ||
* - add params handled by this form to this list | ||
* - any params from other forms you want to clear on submit | ||
*/ | ||
exclude?: Array<string | undefined>; | ||
}; | ||
|
||
/** | ||
* Include existing query params as hidden inputs in a form. | ||
* | ||
* @example | ||
* A pagination bar that does not clear the search query | ||
* ```tsx | ||
* <Form> | ||
* <ExistingSearchParams exclude={['page']} /> | ||
* <button type="submit" name="page" value="1">1</button> | ||
* <button type="submit" name="page" value="2">2</button> | ||
* <button type="submit" name="page" value="3">3</button> | ||
* </Form> | ||
* ``` | ||
* | ||
* @example | ||
* A search form that clears the page param | ||
* ```tsx | ||
* <Form> | ||
* <ExistingSearchParams exclude={['q', 'page']} /> | ||
* <input type="search" name="q" /> | ||
* </Form> | ||
* ``` | ||
*/ | ||
export function ExistingSearchParams({ exclude }: Props) { | ||
const [searchParams] = useSearchParams(); | ||
const existingSearchParams = [...searchParams.entries()].filter( | ||
([key]) => !exclude?.includes(key), | ||
); | ||
|
||
return ( | ||
<> | ||
{existingSearchParams.map(([key, value]) => { | ||
return ( | ||
<input | ||
key={`${key}=${value}`} | ||
type="hidden" | ||
name={key} | ||
value={value} | ||
/> | ||
); | ||
})} | ||
</> | ||
); | ||
} |