Created
September 28, 2025 14:22
-
-
Save night-fury-rider/0686e24ea659376395ec38af5f475984 to your computer and use it in GitHub Desktop.
TypeScript - Generics
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 from "react"; | |
| import { Select, MenuItem, FormControl, InputLabel, Box } from "@mui/material"; | |
| interface MovieFilterProps<T extends string | number> { | |
| primaryOptionLabel?: string; | |
| primaryOptionValue?: T; | |
| options: T[]; | |
| selectedFilter: T; | |
| setSelectedFilter: React.Dispatch<React.SetStateAction<T>>; | |
| title: string; | |
| } | |
| const MovieFilter = <T extends string | number>({ | |
| primaryOptionLabel, | |
| primaryOptionValue, | |
| options, | |
| selectedFilter, | |
| setSelectedFilter, | |
| title, | |
| }: MovieFilterProps<T>) => { | |
| const getSuffixCharacter = (optionValue: T) => | |
| typeof optionValue === "number" && optionValue < 10 && optionValue > 0 | |
| ? "+" | |
| : ""; | |
| return ( | |
| <Box> | |
| <FormControl variant="outlined"> | |
| <InputLabel>{title}</InputLabel> | |
| <Select | |
| value={selectedFilter} | |
| onChange={(e) => setSelectedFilter(e.target.value as T)} | |
| label={title} | |
| > | |
| <MenuItem value={primaryOptionValue}>{primaryOptionLabel}</MenuItem> | |
| {options.map((optionValue, index) => ( | |
| <MenuItem value={optionValue} key={`${index}_${optionValue}`}> | |
| {optionValue} | |
| {getSuffixCharacter(optionValue)} | |
| </MenuItem> | |
| ))} | |
| </Select> | |
| </FormControl> | |
| </Box> | |
| ); | |
| }; | |
| export default MovieFilter; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment