CustomParamSelect.tsx 2.0 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071
  1. import React from 'react';
  2. import { useFormContext, ErrorMessage } from 'react-hook-form';
  3. import { TopicConfigValue } 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: TopicConfigValue = 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) => (
  35. event: React.ChangeEvent<HTMLSelectElement>
  36. ) => {
  37. triggerValidation(inputName);
  38. onNameChange(index, event.target.value);
  39. };
  40. return (
  41. <>
  42. <label className="label">Custom Parameter</label>
  43. <div className="select is-block">
  44. <select
  45. name={optInputName}
  46. ref={register({
  47. required: 'Custom Parameter is required.',
  48. validate: { unique: (selected) => selectedMustBeUniq(selected) },
  49. })}
  50. onChange={onChange(optInputName)}
  51. disabled={isDisabled}
  52. defaultValue={name}
  53. >
  54. <CustomParamOptions existingFields={existingFields} />
  55. </select>
  56. <p className="help is-danger">
  57. <ErrorMessage errors={errors} name={optInputName} />
  58. </p>
  59. </div>
  60. </>
  61. );
  62. };
  63. export default React.memo(CustomParamSelect);