Created
November 20, 2017 21:40
-
-
Save tiffwu/15e8d2aecf1871ba6dd67f9a225892f2 to your computer and use it in GitHub Desktop.
react-form wrapper for async react-select component
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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