Last active
November 16, 2021 11:47
-
-
Save diego3g/c9be060657cda26d5f7b43a3401ccfb5 to your computer and use it in GitHub Desktop.
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, { useRef, useEffect } from "react"; | |
import Select from "react-select"; | |
import { useField } from "../../../lib"; | |
interface Option { | |
id: string; | |
title: string; | |
} | |
interface Props { | |
name: string; | |
label?: string; | |
options: Option[]; | |
multiple?: boolean; | |
} | |
export default function ReactSelect({ | |
name, | |
label, | |
options, | |
multiple, | |
...rest | |
}: Props) { | |
const ref = useRef(null); | |
const { fieldName, registerField, defaultValue, error } = useField(name); | |
function parseSelectValue(selectValue) { | |
if (!multiple) { | |
return selectValue ? selectValue.id : ""; | |
} | |
return selectValue ? selectValue.map(option => option.id) : []; | |
} | |
useEffect(() => { | |
registerField({ | |
name: fieldName, | |
ref: ref.current, | |
path: "state.value", | |
parseValue: parseSelectValue, | |
clearValue: selectRef => { | |
selectRef.select.clearValue(); | |
} | |
}); | |
}, [ref]); | |
function getDefaultValue() { | |
if (!defaultValue) return null; | |
if (!multiple) { | |
return options.find(option => option.id === defaultValue); | |
} | |
return options.filter(option => defaultValue.includes(option.id)); | |
} | |
return ( | |
<> | |
{label && <label htmlFor={fieldName}>{label}</label>} | |
<Select | |
name={fieldName} | |
aria-label={fieldName} | |
options={options} | |
isMulti={multiple} | |
defaultValue={getDefaultValue()} | |
ref={ref} | |
getOptionValue={option => option.id} | |
getOptionLabel={option => option.title} | |
{...rest} | |
/> | |
{error && <span>{error}</span>} | |
</> | |
); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment