Skip to content

Instantly share code, notes, and snippets.

@SooJungChae
Created March 10, 2021 00:29
Show Gist options
  • Save SooJungChae/6e3883ace37737438d5e0f95518f0be9 to your computer and use it in GitHub Desktop.
Save SooJungChae/6e3883ace37737438d5e0f95518f0be9 to your computer and use it in GitHub Desktop.
react-quill custom image loader in functional component
function imageHandler() {
const input = document.createElement('input');
// Open file select window
input.id = 'tempInput';
input.setAttribute('type', 'file');
input.setAttribute('accept', 'image/*');
input.click();
// When file selected
input.onchange = async () => {
if (!input.files) return;
const file = input.files[0];
if (!file) return;
const formData = new FormData();
formData.append('tempFile', file);
// API post, returns image location as string e.g. 'http://www.example.com/images/foo.png'
const res = await callGetTempImageUrl(formData);
const { status, response } = res;
if (status !== CallAPIResponseType.SUCCESS) {
console.log('Image load fail!');
return false;
}
const { data } = response;
// Set image in editor
if (quillRef.current) {
quillRef.current.focus();
const editor = quillRef.current.getEditor();
const range = editor.getSelection();
const link = data.returnUrl;
const cursorPos = range ? range.index : 0;
editor.insertEmbed(cursorPos, 'image', link);
// Move cursor after image
editor.setSelection({ index: cursorPos + 1, length: 0 });
}
return true;
};
}
const modules = useMemo(() => {
return {
// User just toolbar if no custom toolbar
// toolbar: [
// [{ header: [1, 2, false] }],
// ['bold', 'italic', 'underline', 'strike', 'blockquote'],
// [{ list: 'ordered' }, { list: 'bullet' }, { indent: '-1' }, { indent: '+1' }],
// ['link', 'image'],
// ['clean'],
// ],
toolbar: {
// User handlers, container option if you have custom toolbar
handlers: {
image: imageHandler,
},
container: [
[{ header: [1, 2, false] }],
['bold', 'italic', 'underline', 'strike', 'blockquote'],
[{ list: 'ordered' }, { list: 'bullet' }, { indent: '-1' }, { indent: '+1' }],
['link', 'image'],
['clean'],
],
},
clipboard: {
matchVisual: false,
},
};
}, []);
<ReactQuill
theme="snow"
id={'quill'}
style={{ marginBottom: '10px' }}
modules={modules}
value={content}
onChange={onChangeContent}
ref={quillRef}
/>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment