Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- import React, { PropTypes } from 'react';
- import Select from 'react-select';
- import 'react-select/dist/react-select.css';
- RFReactSelect.defaultProps = {
- multi: false
- };
- RFReactSelect.propTypes = {
- input: PropTypes.shape({
- name: PropTypes.string.isRequired,
- value: PropTypes.string.isRequired,
- onBlur: PropTypes.func.isRequired,
- onFocus: PropTypes.func.isRequired,
- }).isRequired,
- options: PropTypes.array.isRequired,
- multi: PropTypes.bool
- };
- export default function RFReactSelect({ input: { name, value, onBlur, onChange, onFocus }, options, multi }) {
- const transformedValue = transformValue(value, options, multi);
- return (
- <Select
- valueKey="value"
- name={name}
- value={transformedValue}
- multi={multi}
- options={options}
- onChange={multi
- ? multiChangeHandler(onChange)
- : singleChangeHandler(onChange)
- }
- onBlur={() => onBlur(value)}
- onFocus={onFocus}
- />
- );
- }
- function singleChangeHandler(func) {
- return function handleSingleChange(value) {
- func(value ? value.value : '');
- };
- }
- function multiChangeHandler(func) {
- return function handleMultiHandler(values) {
- func(values.map(value => value.value));
- };
- }
- function transformValue(value, options, multi) {
- if (multi && typeof value === 'string') return [];
- const filteredOptions = options.filter(option => {
- return multi
- ? value.indexOf(option.value) !== -1
- : option.value === value;
- });
- return multi ? filteredOptions : filteredOptions[0];
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement