Skip to content

Instantly share code, notes, and snippets.

@pedroribeirodev
Created August 10, 2021 19:25
Show Gist options
  • Save pedroribeirodev/9ca58342ac38fc042a1393682fc2739a to your computer and use it in GitHub Desktop.
Save pedroribeirodev/9ca58342ac38fc042a1393682fc2739a to your computer and use it in GitHub Desktop.
select nativo com react hook form
import React, { useState, useContext } from 'react';
import { FaTimesCircle } from 'react-icons/fa';
import PropTypes from 'prop-types';
import { ThemeContext } from 'styled-components';
import { Container, ErrorMessage } from './styles';
function Select({
label,
name,
options,
register,
defaultValue,
error,
mt,
ml,
mr,
mb
}) {
const theme = useContext(ThemeContext);
const [selectValue, setSelectValue] = useState(defaultValue || '');
const handleChangeSelect = e => setSelectValue(e.target.value);
return (
<Container mt={mt} ml={ml} mr={mr} mb={mb}>
<span>{label}</span>
<select
name={name}
value={selectValue}
ref={register}
onChange={e => handleChangeSelect(e)}
>
{options.map(option => (
<option key={option.id} value={option.value}>
{option.text}
</option>
))}
</select>
{error && (
<ErrorMessage>
<FaTimesCircle
color={theme.bgColors.colorSecondary01}
style={{ margin: '0 5px' }}
/>
<span>{error.message}</span>
</ErrorMessage>
)}
</Container>
);
}
Select.defaultProps = {
label: '',
options: [],
mt: '',
ml: '',
mr: '',
mb: '',
error: undefined,
defaultValue: ''
};
Select.propTypes = {
label: PropTypes.string,
name: PropTypes.string.isRequired,
options: PropTypes.arrayOf(
PropTypes.oneOfType([PropTypes.number, PropTypes.string])
),
register: PropTypes.func.isRequired,
mt: PropTypes.string,
ml: PropTypes.string,
mr: PropTypes.string,
mb: PropTypes.string,
error: PropTypes.objectOf(PropTypes.string),
defaultValue: PropTypes.string
};
export default Select;
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment