Advertisement
Guest User

Untitled

a guest
Oct 21st, 2019
98
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 2.13 KB | None | 0 0
  1. import React from 'react';
  2. import PropTypes from 'prop-types';
  3. import CreatableSelect from 'react-select/creatable';
  4.  
  5. /**
  6. * onChange from Redux Form Field has to be called explicity.
  7. */
  8. function onChangeHandler(func) {
  9. return function handleChange(value) {
  10. func(value ? value.value : '');
  11. };
  12. }
  13.  
  14. /**
  15. * For single select, Redux Form keeps the value as a string, while React Select
  16. * wants the value in the form { value: "grape", label: "Grape" }
  17. */
  18. function transformValue(value, options) {
  19. const selectedOption = options.find((option) => {
  20. return option.value === value;
  21. });
  22.  
  23. return selectedOption;
  24. }
  25.  
  26. const customStyles = {
  27. option: (styles) => ({
  28. ...styles,
  29. fontSize: '14px',
  30. }),
  31. control: (styles, state) => ({
  32. ...styles,
  33. fontSize: '14px',
  34. boxShadow: state.isFocused ? "0 0 4px 2px rgb(59, 153, 252);" : 0,
  35. borderColor: state.isFocused ? "#D0EAE2" : "#CED4DA",
  36. "&:hover": {
  37. borderColor: state.isFocused ? "#D0EAE2" : "#CED4DA"
  38. }
  39. })
  40. };
  41.  
  42. const RFReactSelect = ({ input , options, defaultValue }) => {
  43. const { name, value, onBlur, onChange, onFocus } = input;
  44. const transformedValue = transformValue(value, options);
  45.  
  46. return (
  47. <CreatableSelect
  48. inputId={name}
  49. isClearable
  50. valueKey="value"
  51. name={name}
  52. value={transformedValue}
  53. defaultValue={defaultValue}
  54. options={options}
  55. onChange={onChangeHandler(onChange)}
  56. onBlur={() => onBlur(value)}
  57. onFocus={onFocus}
  58. styles={customStyles}
  59. />
  60. );
  61. }
  62.  
  63. RFReactSelect.defaultProps = {
  64. defaultValue: { value: '', label: '' }
  65. };
  66.  
  67. RFReactSelect.propTypes = {
  68. input: PropTypes.shape({
  69. name: PropTypes.string.isRequired,
  70. value: PropTypes.string.isRequired,
  71. onBlur: PropTypes.func.isRequired,
  72. onChange: PropTypes.func.isRequired,
  73. onFocus: PropTypes.func.isRequired,
  74. }).isRequired,
  75. options: PropTypes.arrayOf(
  76. PropTypes.shape({
  77. value: PropTypes.string.isRequired,
  78. label: PropTypes.string.isRequired
  79. }).isRequired,
  80. ).isRequired,
  81. defaultValue: PropTypes.shape({
  82. value: PropTypes.string,
  83. label: PropTypes.string,
  84. }),
  85. };
  86.  
  87. export default RFReactSelect;
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement