Skip to content

Commit

Permalink
✨ [#52] Update the JSONEdit component to support setting a field value
Browse files Browse the repository at this point in the history
Rather than setting the entire form field values state, it
now allows setting a particular field value. This is required
for the itemsExpression field in SelectBoxes component.
  • Loading branch information
sergei-maertens committed Nov 17, 2023
1 parent 22368d6 commit 1c17154
Showing 1 changed file with 10 additions and 2 deletions.
12 changes: 10 additions & 2 deletions src/components/JSONEdit.tsx
Original file line number Diff line number Diff line change
@@ -1,23 +1,30 @@
import {JSONObject} from '@open-formulieren/types/lib/types';
import clsx from 'clsx';
import {useFormikContext} from 'formik';
import {TextareaHTMLAttributes, useRef, useState} from 'react';

interface JSONEditProps {
data: unknown; // JSON.stringify first argument has the 'any' type in TS itself...
className?: string;
name?: string;
}

const JSONEdit: React.FC<JSONEditProps & TextareaHTMLAttributes<HTMLTextAreaElement>> = ({
data,
className = 'form-control',
name = '',
...props
}) => {
const dataAsJSON = JSON.stringify(data, null, 2);
const inputRef = useRef<HTMLTextAreaElement>(null);

const [value, setValue] = useState(dataAsJSON);
const [JSONValid, setJSONValid] = useState(true);
const {setValues} = useFormikContext();
const {setValues, setFieldValue} = useFormikContext();

// if no name is provided, replace the entire form state, otherwise only set a
// specific value
const updateValue = name ? (v: JSONObject) => setFieldValue(name, v) : setValues;

// synchronize external state changes
const isFocused = inputRef.current == document.activeElement;
Expand All @@ -37,7 +44,8 @@ const JSONEdit: React.FC<JSONEditProps & TextareaHTMLAttributes<HTMLTextAreaElem
setJSONValid(false);
return;
}
setValues(updatedData);

updateValue(updatedData);
};
return (
<>
Expand Down

0 comments on commit 1c17154

Please sign in to comment.