Components
A text field for adding editable captions to media elements like images, videos, and files in a rich-text editor.
Loading preview...
'use client';
import * as React from 'react';
import { Caption, CaptionTextarea } from '@/components/ui/caption';
import * as CaptionKit from '@platejs/caption/react';
import { KEYS } from 'platejs';
import type { PlateElementProps } from 'platejs/react';
import {
Plate,
PlateContent,
PlateElement,
createPlatePlugin,
usePlateEditor,
} from 'platejs/react';
function ImageElement(props: PlateElementProps) {
return (
<PlateElement {...props} className="py-2.5">
<figure className="group relative m-0" contentEditable={false}>
<img
className="block w-full max-w-full rounded-sm object-cover"
src={(props.element as any).url}
alt=""
/>
<Caption align="center">
<CaptionTextarea placeholder="Write a caption..." />
</Caption>
</figure>
{props.children}
</PlateElement>
);
}
const ImagePlugin = createPlatePlugin({
key: KEYS.img,
node: { isElement: true, isVoid: true },
}).withComponent(ImageElement);
const value = [
{
type: KEYS.img,
url: 'https://images.unsplash.com/photo-1712688930249-98e1963af7bd?q=80&w=2070&auto=format&fit=crop',
caption: [{ text: 'Image caption' }],
children: [{ text: '' }],
},
{ type: 'p', children: [{ text: 'Click the caption above to edit it.' }] },
];
export default function CaptionDemo() {
const editor = usePlateEditor({
plugins: [
ImagePlugin,
CaptionKit.CaptionPlugin.configure({
options: { query: { allow: [KEYS.img] } },
}),
],
value,
});
return (
<div className="mx-auto w-full max-w-xl p-6">
<Plate editor={editor}>
<PlateContent className="rounded-md border p-4 focus:outline-none" />
</Plate>
</div>
);
}