@amxchange/grid-view-web-client
Version:
amxchange grid view framework web client in react ( a module extracted from existing jax )
124 lines (113 loc) • 4.19 kB
JSX
import React, { useState, useEffect, useRef } from "react";
import Select from "react-select";
const SelectField = React.forwardRef((props, ref) => {
const {
label,
errorMsg,
value,
containerClass,
defaultValue,
options = [],
onChangeInput,
populateSingleValue = true,
hideSelectIndicatorAndSeparator = false,
...restProps
} = props;
useEffect(() => {
/**
* scenario 1 - if value is passed instead of object and is present in the given options
*/
if (value !== "" && typeof value !== "object") {
let val = options.find(opt => opt.value === value);
if (val) {
onChangeInput(val);
}
}
/**
* scenario 2 - if defaultValue is passed
*/
if (value === "" && defaultValue && defaultValue !== "") {
if (typeof defaultValue === "object") {
let val = options.find(opt => opt.value == defaultValue.value);
if (val) {
onChangeInput(val);
}
} else {
let val = options.find(opt => opt.value == defaultValue);
if (val) {
onChangeInput(val);
}
}
}
/**
* scenario 3 - populate single option
*/
if (!value && !defaultValue && options.length === 1 && populateSingleValue) {
onChangeInput(options[0]);
}
/**
* scenario 4 - for multiple select default values
*/
if (restProps.isMulti && value === "" && Array.isArray(defaultValue)) {
let defaultValues = [];
if (defaultValue.every(val => typeof val === "object")) {
for (let i = 0; i < defaultValue.length; i++) {
let val = options.find(opt => opt.value == defaultValue[i].value);
if (val) {
defaultValues = [...defaultValues, val];
}
}
onChangeInput(defaultValues);
} else {
for (let i = 0; i < defaultValue.length; i++) {
let val = options.find(opt => opt.value == defaultValue[i]);
if (val) {
defaultValues = [...defaultValues, val];
}
}
onChangeInput(defaultValues);
}
}
/**
* scenario 5 - for multiple select values when controlled true
*/
if (
restProps.isMulti &&
Array.isArray(value) &&
value.find((val) => typeof val === "string")
) {
//in this case, react-select creates an empty val for multiple objects
//so, we are not allowing the dev to set tha input this way, obj is compulsory
onChangeInput([]);
}
return () => {};
}, [value, defaultValue, options]);
const handleInputChange = newVal => {
onChangeInput(newVal);
};
return (
<div className={`input-field-sec select-box ${errorMsg ? "error-field" : ""} ${containerClass || ""}`}>
<label
style={{
...(!label ? { display: "none" } : {})
}}
>
{label || ""}
</label>
<Select
className="react-select"
classNamePrefix="react-select"
innerRef={ref}
options={options}
value={value}
onChange={handleInputChange}
{...(hideSelectIndicatorAndSeparator
? { components: {...{...{ DropdownIndicator:() => null, IndicatorSeparator:() => null }} } }
: {})}
{...restProps}
/>
{errorMsg && <span className="helperTextError">{errorMsg}</span>}
</div>
);
});
export default SelectField;