CustomParamSelect.tsx 1.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869
  1. import React from 'react';
  2. import { useFormContext, ErrorMessage } from 'react-hook-form';
  3. import { TopicFormCustomParam } from 'redux/interfaces';
  4. import CustomParamOptions from './CustomParamOptions';
  5. import { INDEX_PREFIX } from './CustomParams';
  6. interface Props {
  7. isDisabled: boolean;
  8. index: string;
  9. name: string;
  10. existingFields: string[];
  11. onNameChange: (inputName: string, name: string) => void;
  12. }
  13. const CustomParamSelect: React.FC<Props> = ({
  14. isDisabled,
  15. index,
  16. name,
  17. existingFields,
  18. onNameChange,
  19. }) => {
  20. const { register, errors, getValues, triggerValidation } = useFormContext();
  21. const optInputName = `${index}[name]`;
  22. const selectedMustBeUniq = (selected: string) => {
  23. const values = getValues({ nest: true });
  24. const customParamsValues: TopicFormCustomParam = values.customParams;
  25. const valid = !Object.entries(customParamsValues).some(
  26. ([key, customParam]) => {
  27. return (
  28. `${INDEX_PREFIX}.${key}` !== index && selected === customParam.name
  29. );
  30. }
  31. );
  32. return valid || 'Custom Parameter must be unique';
  33. };
  34. const onChange = (inputName: string) => (event: any) => {
  35. triggerValidation(inputName);
  36. onNameChange(index, event.target.value);
  37. };
  38. return (
  39. <>
  40. <label className="label">Custom Parameter</label>
  41. <div className="select is-block">
  42. <select
  43. name={optInputName}
  44. ref={register({
  45. required: 'Custom Parameter is required.',
  46. validate: { unique: (selected) => selectedMustBeUniq(selected) },
  47. })}
  48. onChange={onChange(optInputName)}
  49. disabled={isDisabled}
  50. defaultValue={name}
  51. >
  52. <CustomParamOptions existingFields={existingFields} />
  53. </select>
  54. <p className="help is-danger">
  55. <ErrorMessage errors={errors} name={optInputName} />
  56. </p>
  57. </div>
  58. </>
  59. );
  60. };
  61. export default React.memo(CustomParamSelect);