Skip to content

Instantly share code, notes, and snippets.

@Fcmam5
Last active January 31, 2021 05:12
Show Gist options
  • Select an option

  • Save Fcmam5/2568c1e1dab002adb43cd4a1121e44db to your computer and use it in GitHub Desktop.

Select an option

Save Fcmam5/2568c1e1dab002adb43cd4a1121e44db to your computer and use it in GitHub Desktop.
Quill-React embed image example with a functional component
export const modules = {
toolbar: {
container: [
[{ header: [1, 2, false] }],
['bold', 'italic', 'underline', 'strike', 'blockquote'],
[{ list: 'ordered' }, { list: 'bullet' }, { indent: '-1' }, { indent: '+1' }],
['link', 'image', 'color'],
['clean'],
],
},
};
export const formats = [
'header',
'bold',
'italic',
'underline',
'strike',
'blockquote',
'list',
'bullet',
'indent',
'link',
'image',
'color',
];
import React, { useEffect } from 'react';
import PropTypes from 'prop-types';
import ReactQuill from 'react-quill';
import 'react-quill/dist/quill.snow.css';
import { modules, formats } from './config';
function RichEditor({ store, attribute, placeholder }) {
let quillRef = null;
let reactQuillRef = null;
modules.toolbar.handlers = {
image: () => {
const range = quillRef.getSelection();
const position = range ? range.index : 0;
// TODO Replace it with a fancier component :)
const value = prompt('What is the image URL');
if (value) {
quillRef.insertEmbed(position, 'image', value, 'user');
}
},
};
useEffect(() => {
if (typeof reactQuillRef.getEditor !== 'function') return;
if (quillRef != null) return;
const ref = reactQuillRef.getEditor();
if (ref != null) quillRef = ref;
}, []);
const handleChange = txt => {
store.setAttr(attribute, txt);
};
return (
<ReactQuill
value={store[attribute]}
onChange={handleChange}
placeholder={placeholder}
modules={modules}
formats={formats}
ref={el => {
reactQuillRef = el;
}}
/>
);
}
RichEditor.propTypes = {
attribute: PropTypes.string.isRequired,
placeholder: PropTypes.oneOfType([PropTypes.string, PropTypes.node]),
};
RichEditor.defaultProps = {
placeholder: '',
};
export default RichEditor;
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment