Skip to content

Instantly share code, notes, and snippets.

@AdventureBear
Created August 30, 2024 15:18
Show Gist options
  • Save AdventureBear/0b46d474cfbbcda4c816c812a6df11c1 to your computer and use it in GitHub Desktop.
Save AdventureBear/0b46d474cfbbcda4c816c812a6df11c1 to your computer and use it in GitHub Desktop.
Radix UI for components, Tailwind for styling and react-select for multi-select & clearable select box
'use client'
import React, {useEffect, useState} from 'react'
import Select from "react-select";
import {EventType} from "@prisma/client"
import {useRouter} from "next/navigation";
import {Button, Flex} from "@radix-ui/themes";
const EventFilter = ({athleteList}:{athleteList: {name: string, id:number}[] }) => {
const router = useRouter()
// States for the filters
const [selectedEventTypes, setSelectedEventTypes] = useState<string[]>([]);
const [selectedAthletes, setSelectedAthletes] = useState<number[]>([]);
const [queryString, setQueryString] = useState('')
console.log(selectedAthletes, selectedEventTypes)
useEffect(() => {
let fullQueryString = '';
if (selectedEventTypes.length > 0) {
fullQueryString += `type=${selectedEventTypes.join('&type=')}`;
}
if (selectedAthletes.length > 0) {
if (fullQueryString.length > 0) fullQueryString += '&';
fullQueryString += `athleteId=${selectedAthletes.join('&athleteId=')}`;
}
setQueryString(fullQueryString)
// If all filters are cleared, push an empty query string
// router.push(`/events${fullQueryString.length > 0 ? `?${fullQueryString}` : ''}`);
}, [selectedEventTypes, selectedAthletes, router, queryString]);
const handleSubmit=()=>{
router.push(`/events${queryString.length > 0 ? `?${queryString}` : ''}`);
}
const eventTypeOptions:{value: EventType, label: EventType}[] = Object.keys(EventType).map((eventType) => ({
value: eventType as EventType,
label: eventType as EventType
}))
const athleteOptions = athleteList.map(athlete => ({
value: athlete.id,
label: athlete.name
}));
return (
<Flex direction="column" gap="2" className="mb-2">
<Select
instanceId="event-types"
onChange={(eventType) => {
const selected = eventType ? eventType.map(option => option.value) : [];
setSelectedEventTypes(Array.isArray(selected) ? selected : [selected]);
}}
className="w-full"
placeholder="Event Type ..."
isClearable
isMulti
options={eventTypeOptions}
/>
<Select
instanceId="athlete-ids"
onChange={(athlete) => {
const selected = athlete ? athlete.map(option => option.value) : [];
setSelectedAthletes(Array.isArray(selected) ? selected : [selected]);
}}
className="w-full"
placeholder="Athlete..."
isClearable
isMulti
options={athleteOptions}
/>
<Button onClick={handleSubmit} className="md:w-1/5">
Apply Filters
</Button>
</Flex>
)
}
export default EventFilter
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment