Open RamazaniMwemedi opened 11 months ago
You should create an <input/>
element and get the file from it, here's an example.
I haven't tested it, and it's a bit convoluted
As stated on #292 the pasting image seems to have an unexpected behavior. There might be a memory leak since the promise never times out
import 'react-markdown-editor-lite/lib/index.css';
import Editor from 'react-markdown-editor-lite';
interface MarkdownEditorComponentProps {}
const MarkdownEditorComponent: FunctionComponent<
MarkdownEditorComponentProps
> = () => {
const inputFile = useRef<HTMLInputElement | null>(null);
const promiseResolveRef =
useRef<(value: { url: string; text?: string | undefined }) => void>();
const promiseRejectRef = useRef<(reason?: any) => void>();
// This is a custom function that handles the image upload, yours will differ
const uploadFile = async (file: File) => {
const attachmentsRecord = await attachFile(file);
const imageUrl = await getAttachmentFileURL(
attachmentsRecord.files[attachmentsRecord.files.length - 1],
);
return imageUrl;
};
const handleFileChange = async (event: ChangeEvent<HTMLInputElement>) => {
const selectedFile = event.target.files?.[0];
if (selectedFile && promiseResolveRef.current) {
try {
const imageUrl = await uploadFile(selectedFile); // Upload the file to a server or check out https://developer.mozilla.org/pt-BR/docs/Web/API/FileReader
promiseResolveRef.current({
text: selectedFile.name,
url: imageUrl,
});
} catch (error) {
if (promiseRejectRef.current)
promiseRejectRef.current(
new Error(
`Promise rejected, erro:`,
error as ErrorOptions
)
);
console.error('Error reading file:', error);
}
}
};
const onCustomImageUpload = async (
event: any
): Promise<{ url: string; text?: string | undefined }> => {
inputFile.current?.click();
return new Promise((resolve, reject) => {
promiseResolveRef.current = resolve;
promiseRejectRef.current = reject;
});
};
return (
<>
<input
type="file"
id="file"
ref={inputFile}
style={{ display: 'none' }}
onChange={handleFileChange}
/>
<Editor
onCustomImageUpload={onCustomImageUpload}
/>
</>
);
};
export default MarkdownEditorComponent;
Have a look at the demo they supplied https://github.com/HarryChen0506/react-markdown-editor-lite/blob/dependabot/npm_and_yarn/get-func-name-2.0.2/demo/basic.md
Please note 提问前请注意