UNPKG

@eureca/eureca-ui

Version:

UI component library of Eureca's user and admin apps

108 lines (98 loc) 2.51 kB
import React, { useState, useRef, useEffect } from 'react'; import PropTypes from 'prop-types'; import { makeStyles } from '@material-ui/core/styles'; import { FormControl, FormHelperText, MenuItem, Select as MaterialSelect, InputLabel, } from '@material-ui/core'; import { colors } from '../../theme/colors'; const useStyles = makeStyles({ labelRoot: { color: colors.gray2, fontSize: '.875rem', }, labelShrink: { color: colors.gray3, }, helperText: { color: colors.gray3, fontWeight: 300, letterSpacing: 'normal', }, }); function Select({ name = '', label = '', options = [], value, onChange, error, disabled, helperText, optionLabel = 'name', optionValue = 'id', optionId = 'id', ...props }) { const classes = useStyles(); const inputLabel = useRef(null); const [labelWidth, setLabelWidth] = useState(0); const handleChange = event => { if (onChange) { onChange(event.target.value); } }; useEffect(() => { setLabelWidth(inputLabel.current.offsetWidth); }, []); return ( <FormControl variant="outlined" fullWidth> <InputLabel classes={{ root: classes.labelRoot, shrink: classes.labelShrink }} ref={inputLabel} htmlFor={`outlined-${name || label}-simple-select`} error={error} disabled={disabled} > {label} </InputLabel> <MaterialSelect fullWidth value={value} onChange={handleChange} labelWidth={labelWidth} error={error} disabled={disabled} {...props} inputProps={{ name: `${name}`, id: `outlined-${name || label}-simple-select`, }} > {options.map(option => ( <MenuItem value={option[optionValue]} key={option[optionId]}> {option[optionLabel]} </MenuItem> ))} </MaterialSelect> <FormHelperText error={error} disabled={disabled} classes={{ root: classes.helperText }}> {helperText} </FormHelperText> </FormControl> ); } Select.propTypes = { name: PropTypes.string.isRequired, label: PropTypes.string.isRequired, color: PropTypes.string, inputProps: PropTypes.object, options: PropTypes.arrayOf(PropTypes.object).isRequired, value: PropTypes.oneOfType([PropTypes.string, PropTypes.number, PropTypes.bool]).isRequired, onChange: PropTypes.func.isRequired, error: PropTypes.bool, disabled: PropTypes.bool, }; export { Select };