@etsoo/materialui
Version:
TypeScript Material-UI Implementation
51 lines (50 loc) • 1.65 kB
JavaScript
import { jsxs as _jsxs, jsx as _jsx } from "react/jsx-runtime";
import React from "react";
import { InputField } from "../InputField";
import Typography from "@mui/material/Typography";
function parseJson(value) {
if (value) {
try {
return JSON.parse(value);
}
catch (error) {
return undefined;
}
}
return undefined;
}
/**
* Textarea field creator
* type: json
* @returns Component
*/
export const FieldJson = ({ field, mref, onChange, defaultValue }) => {
// Ref
const inputRef = React.useRef();
const getValue = () => parseJson(inputRef.current?.value);
const setValue = (value) => {
if (inputRef.current) {
const obj = typeof value === "object"
? value
: typeof value === "string"
? parseJson(value)
: undefined;
inputRef.current.value = obj ? JSON.stringify(obj, null, 4) : "";
}
};
React.useImperativeHandle(mref, () => ({
getValue,
setValue
}));
React.useEffect(() => {
if (defaultValue == null)
return;
setValue(defaultValue);
}, [defaultValue]);
// Name
const name = field.name;
if (!name) {
return (_jsxs(Typography, { children: ["No name for FieldJson ", JSON.stringify(field)] }));
}
return (_jsx(InputField, { label: field.label ?? "", helperText: field.helperText, name: name, fullWidth: true, multiline: true, rows: 4, inputProps: { maxLength: 1280 }, inputRef: inputRef, onChange: () => onChange(name, getValue()), ...field.mainSlotProps }));
};