Skip to content

Instantly share code, notes, and snippets.

@jonshipman
Last active August 18, 2020 19:20
Show Gist options
  • Save jonshipman/9bd04125a82b1f572d4ebd77f41aaf3a to your computer and use it in GitHub Desktop.
Save jonshipman/9bd04125a82b1f572d4ebd77f41aaf3a to your computer and use it in GitHub Desktop.
Key
const keyGeneration = ({ loading, value }) => {
return loading
? `loading-${value}-${new Date().getTime()}`
: `loaded-${value}-${new Date().getTime()}`;
};
const Select = forwardRef(function Select(
{
id,
label,
onChange = () => true,
options = {},
value = "",
className = "",
children,
placeholder,
loading,
...props
},
ref
) {
return (
<div className={className}>
{label && (
<label htmlFor={id} className={labelClassName}>
{label}:{" "}
</label>
)}
<select
ref={ref}
onChange={(e) => onChange(e.currentTarget.value)}
id={id}
defaultValue={value}
className={fieldClassName}
style={{ flexGrow: 1 }}
key={keyGeneration({ loading, value })}
{...props}
>
{placeholder && <option value="">{placeholder}</option>}
{options.map((option) => (
<option
key={keyGeneration({ loading, value: option.value })}
value={option.value}
>
{option.label}
</option>
))}
</select>
{children}
</div>
);
});
const LocationSelector = ({ value, onChange = () => {}, ...props }) => {
const {
closest: { databaseId },
loading,
} = useClientLocation();
const { locations } = useAcculynx();
const { location: locationPage } = useContext(LocationDataContext);
useEffect(() => {
if (locationPage.databaseId) {
onChange(locationPage.databaseId);
} else if (databaseId) {
onChange(databaseId);
}
}, [onChange, databaseId, locationPage]);
const options = useMemo(() => {
const result = [];
locations.forEach((node) => {
result.push({
value: node.databaseId,
label: `Location: ${node.title}`,
});
});
return result;
}, [locations]);
return (
<Select
id="locationId"
placeholder="Location"
loading={loading}
onChange={onChange}
value={value || databaseId}
options={options}
{...props}
/>
);
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment