Skip to content

Instantly share code, notes, and snippets.

@tiffwu
Created November 20, 2017 21:40
Show Gist options
  • Save tiffwu/15e8d2aecf1871ba6dd67f9a225892f2 to your computer and use it in GitHub Desktop.
Save tiffwu/15e8d2aecf1871ba6dd67f9a225892f2 to your computer and use it in GitHub Desktop.
react-form wrapper for async react-select component
import React, { PureComponent } from 'react';
import PropTypes from 'prop-types';
import { FormField } from 'react-form';
import Select from 'react-select';
import 'react-select/dist/react-select.css';
// WIP custom message component
const Message = ({ color, message }) => (
<div style={{ color }}>
<small>{JSON.stringify(message)}</small>
</div>
);
class Autocomplete extends PureComponent {
constructor(props) {
super(props);
this.handleChange = this.handleChange.bind(this);
this.handleBlur = this.handleBlur.bind(this);
}
handleChange(selected) {
const { fieldApi: { setValue } } = this.props;
setValue(selected);
}
handleBlur() {
this.props.fieldApi.setTouched();
}
render() {
const {
getOptions,
placeholder,
fieldApi: {
getError,
getWarning,
getSuccess,
getFieldName,
getValue
},
...rest
} = this.props;
const error = getError();
const warning = getWarning();
const success = getSuccess();
return (
<div>
<Select.Async
name={getFieldName()}
multi
value={getValue()}
onChange={this.handleChange}
onBlur={this.handleBlur}
loadOptions={getOptions}
placeholder={placeholder}
{...rest}
/>
{error && <Message color="red" message={error} />}
{!error && warning && <Message color="orange" message={warning} />}
{!error && !warning && success && <Message color="green" message={success} />}
</div>
);
}
}
Autocomplete.propTypes = {
getOptions: PropTypes.func.isRequired,
placeholder: PropTypes.string,
fieldApi: PropTypes.object.isRequired
};
Autocomplete.defaultProps = {
placeholder: undefined
};
export default FormField(Autocomplete);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment