Last active
January 31, 2021 05:12
-
-
Save Fcmam5/2568c1e1dab002adb43cd4a1121e44db to your computer and use it in GitHub Desktop.
Quill-React embed image example with a functional component
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| 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', | |
| ]; |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| 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