Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- import React from 'react';
- import PropTypes from 'prop-types';
- import CreatableSelect from 'react-select/creatable';
- /**
- * onChange from Redux Form Field has to be called explicity.
- */
- function onChangeHandler(func) {
- return function handleChange(value) {
- func(value ? value.value : '');
- };
- }
- /**
- * For single select, Redux Form keeps the value as a string, while React Select
- * wants the value in the form { value: "grape", label: "Grape" }
- */
- function transformValue(value, options) {
- const selectedOption = options.find((option) => {
- return option.value === value;
- });
- return selectedOption;
- }
- const customStyles = {
- option: (styles) => ({
- ...styles,
- fontSize: '14px',
- }),
- control: (styles, state) => ({
- ...styles,
- fontSize: '14px',
- boxShadow: state.isFocused ? "0 0 4px 2px rgb(59, 153, 252);" : 0,
- borderColor: state.isFocused ? "#D0EAE2" : "#CED4DA",
- "&:hover": {
- borderColor: state.isFocused ? "#D0EAE2" : "#CED4DA"
- }
- })
- };
- const RFReactSelect = ({ input , options, defaultValue }) => {
- const { name, value, onBlur, onChange, onFocus } = input;
- const transformedValue = transformValue(value, options);
- return (
- <CreatableSelect
- inputId={name}
- isClearable
- valueKey="value"
- name={name}
- value={transformedValue}
- defaultValue={defaultValue}
- options={options}
- onChange={onChangeHandler(onChange)}
- onBlur={() => onBlur(value)}
- onFocus={onFocus}
- styles={customStyles}
- />
- );
- }
- RFReactSelect.defaultProps = {
- defaultValue: { value: '', label: '' }
- };
- RFReactSelect.propTypes = {
- input: PropTypes.shape({
- name: PropTypes.string.isRequired,
- value: PropTypes.string.isRequired,
- onBlur: PropTypes.func.isRequired,
- onChange: PropTypes.func.isRequired,
- onFocus: PropTypes.func.isRequired,
- }).isRequired,
- options: PropTypes.arrayOf(
- PropTypes.shape({
- value: PropTypes.string.isRequired,
- label: PropTypes.string.isRequired
- }).isRequired,
- ).isRequired,
- defaultValue: PropTypes.shape({
- value: PropTypes.string,
- label: PropTypes.string,
- }),
- };
- export default RFReactSelect;
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement