Skip to content

Instantly share code, notes, and snippets.

@diego3g
Last active November 16, 2021 11:47
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save diego3g/c9be060657cda26d5f7b43a3401ccfb5 to your computer and use it in GitHub Desktop.
Save diego3g/c9be060657cda26d5f7b43a3401ccfb5 to your computer and use it in GitHub Desktop.
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