dashboard/src/components/select.tsx

70 lines
1.4 KiB
TypeScript
Raw Normal View History

2021-06-30 00:56:01 +02:00
import React from "react";
2021-11-23 17:50:30 +01:00
import styled from "styled-components";
2021-06-30 00:56:01 +02:00
export interface IItemProps {
label: string;
value: any;
}
export interface ISelectProps {
items: Array<IItemProps>;
onChange: (item: any) => void;
2021-07-11 15:58:42 +02:00
current?: string;
2021-06-30 00:56:01 +02:00
className?: string;
2021-07-11 15:58:42 +02:00
testId?: string;
2021-06-30 00:56:01 +02:00
}
2021-11-23 17:50:30 +01:00
const List = styled.select`
border-radius: 0;
padding: 0.5rem;
`;
2021-06-30 00:56:01 +02:00
const update = (
items: Array<IItemProps>,
onChange: (item: any) => void,
e: React.ChangeEvent<HTMLSelectElement>,
) => {
onChange(items.find((item) => item.value.toString() === e.target.value));
};
2021-07-11 15:58:42 +02:00
const Select = ({
items,
onChange,
current,
className,
testId,
}: ISelectProps) => (
2021-11-23 17:50:30 +01:00
<List
2021-07-11 15:58:42 +02:00
data-testid={"select" + (testId ? "-" + testId : "")}
2021-06-30 00:56:01 +02:00
onChange={(e) => update(items, onChange, e)}
className={className}
>
{items.map(({ label, value }, index) => {
2021-11-19 04:29:24 +01:00
if (label === current) {
2021-11-20 12:39:29 +01:00
return (
<option
data-testid={"option-" + (testId ? testId + "-" : "") + index}
key={[label, index].join("")}
value={value.toString()}
selected
>
{label}
</option>
2021-11-20 12:39:29 +01:00
);
2021-11-19 04:29:24 +01:00
} else {
2021-11-20 12:39:29 +01:00
return (
<option
data-testid={"option-" + (testId ? testId + "-" : "") + index}
key={[label, index].join("")}
value={value.toString()}
>
{label}
</option>
2021-11-20 12:39:29 +01:00
);
2021-11-19 04:29:24 +01:00
}
})}
2021-11-23 17:50:30 +01:00
</List>
2021-06-30 00:56:01 +02:00
);
export default Select;