Created
December 17, 2021 15:46
-
-
Save mitchallen/a7b53c713110fa2a11797a087add9718 to your computer and use it in GitHub Desktop.
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
// File: UseDropdownInput.tsx | |
// Author: Mitch Allen | |
import {FormControl, InputLabel, Select, Input, FormHelperText, SelectChangeEvent, MenuItem} from "@mui/material"; | |
import {ReactNode, useCallback, useState} from "react"; | |
/* | |
// App() | |
let dProps = useDropdownElement({ | |
style: {}, | |
stateName: 'xFactor', | |
menuList: [ | |
{key: '0', title: 'X Alpha', value: 'alpha'}, | |
{key: '1', title: 'X Beta', value: 'beta'}, | |
], | |
label: 'X Factor', | |
helperText: 'An Experiment', | |
init: 'alpha', | |
}); | |
// render | |
<DropdownElement {...dProps} /> | |
*/ | |
export interface DropdownMenuItemProps { | |
key: string | number, | |
title: string, | |
value: string, | |
} | |
export interface DropdownElementProps { | |
style: any, | |
stateName: string, // must match variable | |
label: string, | |
value: string, | |
menuList: DropdownMenuItemProps[], | |
helperText: string, | |
onChange: ((event: SelectChangeEvent<string>, child: ReactNode) => void), | |
} | |
export function DropdownElement( | |
props: DropdownElementProps | |
) { | |
const dropdownList = props.menuList.map((item: DropdownMenuItemProps) => ( | |
<MenuItem key={item.key} value={item.value} > | |
{item.title} | |
</MenuItem> )); | |
return ( | |
<FormControl | |
style={props.style} | |
> | |
<InputLabel htmlFor={`${props.stateName}-placeholder`}>{props.label}</InputLabel> | |
<Select | |
value={props.value} | |
onChange={props.onChange} | |
// name MUST match state name | |
input={<Input name={props.stateName} id={`${props.stateName}-placeholder`} />} | |
> | |
{dropdownList} | |
</Select> | |
<FormHelperText>{props.helperText}</FormHelperText> | |
</FormControl> | |
) | |
} | |
// passed to use hook | |
export interface DropdownInput { | |
style: any, | |
stateName: string, | |
menuList: DropdownMenuItemProps[], | |
label: string, | |
helperText?: string, | |
init: string, | |
} | |
export function useDropdownElement(options: DropdownInput): DropdownElementProps { | |
let { | |
style = {}, | |
stateName = '', | |
label = 'Text', | |
menuList = [], | |
helperText = undefined, | |
init = '', | |
} = options; | |
if( helperText === undefined ) { | |
helperText = `Select ${label}`; | |
} | |
const [value, setValue] = useState(init); | |
const onChange = useCallback((event) => { | |
setValue(event.target.value); | |
}, []); | |
return { | |
style, | |
label, | |
menuList, | |
stateName, | |
value, | |
onChange, | |
helperText, | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment