Skip to content

Instantly share code, notes, and snippets.

@JodiWarren
Last active December 14, 2021 18:14
Show Gist options
  • Save JodiWarren/b071219f2e0b65dd67d0db37320a8f85 to your computer and use it in GitHub Desktop.
Save JodiWarren/b071219f2e0b65dd67d0db37320a8f85 to your computer and use it in GitHub Desktop.
Simple monospace text area for Sanity
import React from "react";
import { FormField } from "@sanity/base/components";
import { Card, Label, Stack, TextArea } from "@sanity/ui";
import PatchEvent, { set, unset } from "@sanity/form-builder/PatchEvent";
import { useId } from "@reach/auto-id"; // hook to generate unique IDs
const MonospaceTextArea = React.forwardRef((props, ref) => {
const {
type, // Schema information
value, // Current field value
readOnly, // Boolean if field is not editable
placeholder, // Placeholder text from the schema
markers, // Markers including validation rules
presence, // Presence information for collaborative avatars
compareValue, // Value to check for "edited" functionality
onFocus, // Method to handle focus state
onBlur, // Method to handle blur state
onChange, // Method to handle patch events
} = props;
const inputId = useId();
// Creates a change handler for patching data
const handleChange = React.useCallback(
// useCallback will help with performance
(event) => {
const inputValue = event.currentTarget.value; // get current value
// if the value exists, set the data, if not, unset the data
onChange(PatchEvent.from(inputValue ? set(inputValue) : unset()));
},
[onChange]
);
return (
<Stack space={2}>
<Label>{props.type.title}</Label>
<Card padding={4}>
<FormField
description={type.description}
title={type.title}
__unstable_markers={markers} // Handles all markers including validation
__unstable_presence={presence} // Handles presence avatars
compareValue={compareValue} // Handles "edited" status>
inputId={inputId} // Allows the label to connect to the input field
>
<TextArea
id={inputId} // A unique ID for this input
fontSize={[2, 2, 2, 3]}
padding={[3, 3, 4]}
style={{ fontFamily: "monospace" }}
value={value} // Current field value
readOnly={readOnly} // If "readOnly" is defined make this field read only
placeholder={placeholder} // If placeholder is defined, display placeholder text
onChange={handleChange} // A function to call when the input value changes
onFocus={onFocus} // Handles focus events
onBlur={onBlur} // Handles blur events
ref={ref}
rows={type.rows}
/>
</FormField>
</Card>
</Stack>
);
});
export default MonospaceTextArea;
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment