irisrad-ui
Version:
UI elements developered for IRIS R&D Group Inc
87 lines (81 loc) • 3.06 kB
JavaScript
import React, { useState, useEffect, useRef } from "react";
import "../../style/styles.css";
import Select from "./Select";
import PropTypes from "prop-types";
const IrisSelect = React.memo(function ({
className = "",
label, //string value of the select element
value, // string value of the selected option's value
options, // array of object in shape {value: string, label: string}
onChange, // onChange function when selection is changed
valueField, // the property name whose value is the value that would be send to server
labelField, // the property name whose value would be displayed to the user
...props
}) {
const irisCustomSelectRef = useRef(null);
const [matchedValue, setMatchedValue] = useState(null);
useEffect(() => {
let Element;
if (irisCustomSelectRef && irisCustomSelectRef.current) {
const { current } = irisCustomSelectRef;
current.onChange = onChange;
Element = new Select(current);
}
return () => {
Element.unregisterListeners();
};
}, [options]);
let wrapperClassName = "iris-input-wrapper";
if (typeof className === "string" && className !== "") {
wrapperClassName += " " + className;
}
return (
<div className={wrapperClassName} {...props}>
<div
ref={irisCustomSelectRef}
className={[
"iris-custom-select-wrapper",
className ? className : "",
].join(" ")}
// className="iris-custom-select-wrapper"
>
<div className="iris-custom-select-container iris-input__input-field">
{/* label shows the select label title */}
<div className="iris-custom-select-label-wrapper">
<h2 className="iris-custom-select-label">
{options.find((o) => o[valueField] === value)?.[labelField]}
</h2>
<div className="arrow-down"></div>
</div>
<ul className="iris-custom-select-list">
{options.map((option) => (
<li
value={option[valueField]}
key={option[valueField]}
selected={option[valueField] === value}
>
{option[labelField]}
</li>
))}
</ul>
{/* label for the element ie: please select a blablabla */}
<label className="iris-input__label">{label}</label>
</div>
</div>
</div>
);
}, isEqual);
function isEqual(nextProps, prevProps) {
const prevOptionsString = JSON.stringify(prevProps.options);
const nextOptionsString = JSON.stringify(nextProps.options);
return prevOptionsString === nextOptionsString;
}
IrisSelect.propTypes = {
className: PropTypes.string,
label: PropTypes.string,
value: PropTypes.oneOfType([PropTypes.string, PropTypes.number]),
options: PropTypes.arrayOf(PropTypes.object).isRequired,
valueField: PropTypes.string.isRequired,
labelField: PropTypes.string.isRequired,
};
export { IrisSelect };