CustomParamValue.tsx 1.4 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061
  1. import React from 'react';
  2. import { useFormContext, ErrorMessage } from 'react-hook-form';
  3. import { CUSTOM_PARAMS_OPTIONS } from './customParamsOptions';
  4. import { isFirstParam } from './CustomParams';
  5. interface Props {
  6. isDisabled: boolean;
  7. index: string;
  8. name: string;
  9. defaultValue: string;
  10. }
  11. const CustomParamValue: React.FC<Props> = ({
  12. isDisabled,
  13. index,
  14. name,
  15. defaultValue,
  16. }) => {
  17. const { register, unregister, errors, watch, setValue } = useFormContext();
  18. const selectInputName = `${index}[name]`;
  19. const valInputName = `${index}[value]`;
  20. const selectedParamName = watch(selectInputName, name);
  21. React.useEffect(() => {
  22. if (selectedParamName) {
  23. setValue(
  24. valInputName,
  25. CUSTOM_PARAMS_OPTIONS[selectedParamName].defaultValue,
  26. true
  27. );
  28. }
  29. }, [selectedParamName]);
  30. React.useEffect(() => {
  31. if (isFirstParam(index)) {
  32. unregister(valInputName);
  33. }
  34. });
  35. return (
  36. <>
  37. <label className="label">Value</label>
  38. <input
  39. className="input"
  40. placeholder="Value"
  41. ref={register({
  42. required: 'Value is required.',
  43. })}
  44. name={valInputName}
  45. defaultValue={defaultValue}
  46. autoComplete="off"
  47. disabled={isDisabled}
  48. />
  49. <p className="help is-danger">
  50. <ErrorMessage errors={errors} name={valInputName} />
  51. </p>
  52. </>
  53. );
  54. };
  55. export default React.memo(CustomParamValue);