Git Product home page Git Product logo

suneditor-react's Introduction

suneditor-react

A React Component for SunEditor

NPM JavaScript Style Guide

WYSIWYG HTML Editor

Install

npm

$ npm install --save suneditor suneditor-react # make sure to install suneditor yourself

Getting Started

import React from 'react';
import SunEditor from 'suneditor-react';
import 'suneditor/dist/css/suneditor.min.css'; // Import Sun Editor's CSS File

const MyComponent = props => {
  return (
    <div>
      <p> My Other Contents </p>
      <SunEditor />
    </div>
  );
};
export default MyComponent;

To use suneditor-react with Next.js, please use the dynamic import syntax like below:

import React from 'react';
import dynamic from "next/dynamic";
import 'suneditor/dist/css/suneditor.min.css'; // Import Sun Editor's CSS File

const SunEditor = dynamic(() => import("suneditor-react"), {
  ssr: false,
});

const MyComponent = props => {
  return (
    <div>
      <p> My Other Contents </p>
      <SunEditor />
    </div>
  );
};
export default MyComponent;

Props

About Core

Note: suneditor-react doesn't expose the core object in the callback functions such as onScroll etc. This is because it can be easily retrieved by using the getSunEditorInstance like below.

// Javascript Version

import React, { useRef, useEffect } from "react";
import SunEditor from 'suneditor-react';
import 'suneditor/dist/css/suneditor.min.css'; // Import Sun Editor's CSS File

const MyComponent = props => {
    /**
   * @type {React.MutableRefObject<SunEditor>} get type definitions for editor
   */
    const editor = useRef();

    // The sunEditor parameter will be set to the core suneditor instance when this function is called
    const getSunEditorInstance = (sunEditor) => {
        editor.current = sunEditor;
    };

    return (
        <div>
            <p> My Other Contents </p>
            <SunEditor getSunEditorInstance={getSunEditorInstance} />
        </div>
    );
};
export default MyComponent;
// Typescript Version

import React, { useRef, useEffect } from "react";
import SunEditor from 'suneditor-react';
import SunEditorCore from "suneditor/src/lib/core";
import 'suneditor/dist/css/suneditor.min.css'; // Import Sun Editor's CSS File

const MyComponent = props => {
    const editor = useRef<SunEditorCore>();

    // The sunEditor parameter will be set to the core suneditor instance when this function is called
     const getSunEditorInstance = (sunEditor: SunEditorCore) => {
        editor.current = sunEditor;
    };
    return (
        <div>
            <p> My Other Contents </p>
            <SunEditor getSunEditorInstance={getSunEditorInstance} />
        </div>
    );
};
export default MyComponent;

Basic Settings

lang

Language of editor

//...
render() {
	return <SunEditor lang="en" />
	// Default is en
	// lang prop can be one of the strings provided in this array ["en", "da", "de", "es", "fr", "ja", "ko", "pt_br", "ru", "zh_cn", "ro", "pl", "ckb", "lv", "se", "ua", "he", "it"]
	// Alternatively, an object of your language can be passed to this prop. To learn how to do it refer to the bottom of the page
}

name

HTML form name of editor

This is used to set the HTML form name of the editor. This means on HTML form submission, it will be submitted together with contents of the editor by the name provided.

//...
render() {
	return <SunEditor name="my-editor" />
}

defaultValue

Set Editor's default value

//...
// Sets the default value of the editor.
// This is useful if you don't want the onChange method to be called on render.
// If you want the onChange method to be called on render please use the setContents prop
render() {
	return <SunEditor defaultValue="<p>The editor's default value</p>" />
}

width

Set Editor's width

//...
// px and percentage values are accepted
// eg width="100%" or width="500px"
// default is 100%
render() {
	return <SunEditor width="100%" />
}

height

Set Editor's height

//...
// px and percentage values are accepted
// eg height="100%" or height="100px"
render() {
	return <SunEditor height="100%" />
}

placeholder

Set Editor's placeholder

//...
render() {
	return <SunEditor placeholder="Please type here..." />
}

autoFocus

Should editor focus when initialized

//...
render() {
	return <SunEditor autoFocus={true} />
}

setOptions

Set Options (Settings) for the editor Click to see all options available

Important Note: Some toolbar buttons in suneditor require specific plugins to make them work properly. For example when you specify 'font' in the button list, you will need to import the required plugin from suneditor. suneditor-react by default loads all plugins. To change this behaviour, you can pass a plugin list of only the plugins you would like to load to the plugin option. This will override the default behaviour. To disable the loading of all plugins, set the setAllPlugins prop to false. Read More by clicking this.

import SunEditor, { buttonList } from "suneditor-react";
/*
	buttonList.basic = basic buttons for wordprocessing
	buttonList.formatting = most tools used for formatting - This is the default option
	buttonList.complex = contains most of the buttons
*/
//...
render() {
	return <SunEditor setOptions={{
				    height: 200,
					buttonList: buttonList.formatting // Or Array of button list, eg. [['font', 'align'], ['image']]
                    // plugins: [font] set plugins, all plugins are set by default
					// Other option
			}} />
}

setAllPlugins

Sets all plugins used by buttons. Default value is true

import SunEditor, { buttonList } from "suneditor-react";

//...
render() {
	return <SunEditor setAllPlugins={false} /> // When set to false, you must explicitly set required plugins
}

setContents

Set Editor's Content

Note: To set the initial contents of the editor without calling the onChange event please use the defaultValue prop. setContents is used to set the contents of the editor programmatically. You must be aware that, when the setContents's prop changes, the onChange event is triggered.

//...
render() {
	return <SunEditor setContents="My contents" />
}

appendContents

Append Editor Content

//...
render() {
	return <SunEditor appendContents="My contents" />
}

setDefaultStyle

Set the default style of the editor's edit area

//...
render() {
	return <SunEditor setDefaultStyle="font-family: cursive; font-size: 10px;" />
}

Editor Status

disable

Disable Editor

//...
render() {
    // set to false to enable, default value is false
	return <SunEditor disable={true} />
}

hide

Hide Editor

//...
render() {
    // set to false to hide, default value is false
	return <SunEditor hide={true} />
}

hideToolbar

Hide Editor Toolbar

//...
render() {

    // set to false to hide toolbar, default value is false
	return <SunEditor hideToolbar={true} />
}

disableToolbar

Disable Editor Toolbar

//...
render() {
    // set to false to enable toolbar, default value is false
	return <SunEditor disableToolbar={true} />
}

Events

Note that you need to bind the function passed to the event in the constructor if you are using a class Component, or use arrow functions instead. This is just how react works. Otherwise it won't work. This documentation assumes you bind all your class component methods to the constructor. Eg below:

constructor(props) {
	super(props);
	this.handleChange = this.handleChange.bind(this)
}

onChange

Has the content inside the editor been changed?

handleChange(content){
	console.log(content); //Get Content Inside Editor
}
render() {
	return <SunEditor onChange={handleChange} />
}

onScroll

Has the editor been scrolled?

handleScroll(event){
	console.log(event); //Get the scroll event
}
render() {
	return <SunEditor onScroll={handleScroll} />
}

onClick

Has the editor been clicked?

handleClick(event){
	console.log(event); //Get the click event
}
render() {
	return <SunEditor onClick={handleClick} />
}

onMouseDown

Has the mouse is pressed and not yet released?

handleMouseDown(event){
	console.log(event); //Get the click event
}
render() {
	return <SunEditor onMouseDown={handleMouseDown} />
}

onInput

Has the editor received input?

handleInput(event){
	console.log(event); //Get the click event
}
render() {
	return <SunEditor onInput={handleInput} />
}

onKeyUp

Has the key been released up in the editor?

handleKeyUp(event){
	console.log(event); //Get the keyup event
}
render() {
	return <SunEditor onKeyUp={handleKeyUp} />
}

onFocus

Has the editor been focused?

handleFocus(event){
	console.log(event); //Get the focus event
}
render() {
	return <SunEditor onFocus={handleFocus} />
}

onBlur

Has the editor been blurred?

From the second parameter you can get the contents of the editor.

handleBlur(event, editorContents){
	console.log(event, editorContents); //Get the blur event
}
render() {
	return <SunEditor onBlur={handleBlur} />
}

onLoad

Has the editor been reloaded with setOptions?

handleLoad(reload){
	console.log(reload); //Boolean
}
render() {
	return <SunEditor onLoad={handleLoad} />
}

onKeyDown

Has the key been pressed down in the editor?

handleKeyDown(event){
	console.log(event); //Get the keydown event
}
render() {
	return <SunEditor onKeyDown={handleKeyDown} />
}

onDrop

Has something been dropped into the editor?

handleDrop(event){
	console.log(event); //Get the drop event
}
render() {
	return <SunEditor onDrop={handleDrop} />
}

onImageUploadBefore

Before an image is uploaded into the editor

handleImageUploadBefore(files, info, uploadHandler){
    // uploadHandler is a function
	console.log(files, info)
}
render() {
	return <SunEditor onImageUploadBefore={handleImageUploadBefore} />
}

onImageUpload

Has an image been uploaded into the editor?

handleImageUpload(targetImgElement, index, state, imageInfo, remainingFilesCount){
	console.log(targetImgElement, index, state, imageInfo, remainingFilesCount)
}
render() {
	return <SunEditor onImageUpload={handleImageUpload} />
}

onImageUploadError

Has an image uploaded to the editor resulted in an error?

handleImageUploadError(errorMessage, result){
	console.log(errorMessage, result)
}
render() {
	return <SunEditor onImageUploadError={handleImageUploadError} />
}

onVideoUploadBefore

Before a video is uploaded to the editor

handleVideoUploadBefore(files, info, uploadHandler){
    // uploadHandler is a function
	console.log(files, info)
}
render() {
	return <SunEditor onVideoUploadBefore={handleVideoUploadBefore} />
}

onVideoUpload

Has an image been uploaded into the editor?

handleVideoUpload(targetElement, index, state, info, remainingFilesCount){
	console.log(targetElement, index, state, info, remainingFilesCount)
}
render() {
	return <SunEditor onVideoUpload={handleVideoUpload} />
}

onVideoUploadError

Has a video uploaded to the editor resulted in an error?

handleVideoUploadError(errorMessage, result){
	console.log(errorMessage, result)
}
render() {
	return <SunEditor onVideoUploadError={handleVideoUploadError} />
}

onAudioUploadBefore

Before an audio is uploaded to the editor

handleAudioUploadBefore(files, info, uploadHandler){
    // uploadHandler is a function
	console.log(files, info)
}
render() {
	return <SunEditor onAudioUploadBefore={handleAudioUploadBefore} />
}

onAudioUpload

Has an audio been uploaded into the editor?

handleAudioUpload(targetElement, index, state, info, remainingFilesCount){
	console.log(targetElement, index, state, info, remainingFilesCount)
}
render() {
	return <SunEditor onAudioUpload={handleAudioUpload} />
}

onAudioUploadError

Has an audio uploaded to the editor resulted in an error?

handleAudioUploadError(errorMessage, result){
	console.log(errorMessage, result)
}
render() {
	return <SunEditor onAudioUploadError={handleAudioUploadError} />
}

onResizeEditor

Has the editor been resized?

handleOnResizeEditor(height, prevHeight){
	console.log(height, prevHeight)
}
render() {
	return <SunEditor onResizeEditor={handleOnResizeEditor} />
}

onCopy

Has something been copied from the suneditor?

handleCopy(e, clipboardData){
	console.log(e, clipboardData)
}
render() {
	return <SunEditor onCopy={handleCopy} />
}

onCut

Has something been cut from the suneditor?

handleCut(e, clipboardData){
	console.log(e, clipboardData)
}
render() {
	return <SunEditor onCut={handleCut} />
}

onPaste

Has something been pasted into the suneditor?

handlePaste(e, cleanData, maxCharCount){
	console.log(e, cleanData, maxCharCount)
}
render() {
	return <SunEditor onPaste={handlePaste} />
}

imageUploadHandler

Replaces the default callback function of the image upload

imageUploadHandler(xmlHttpRequest, info, core){
	console.log(xmlHttpRequest, info, core)
}
render() {
	return <SunEditor imageUploadHandler={imageUploadHandler} />
}

toggleCodeView

An event when toggling between code view and wysiwyg view

toggleCodeView(isCodeView){
	console.log(isCodeView)
}
render() {
	return <SunEditor toggleCodeView={toggleCodeView} />
}

toggleFullScreen

An event when toggling full screen

toggleFullScreen(isFullScreen){
	console.log(isFullScreen)
}
render() {
	return <SunEditor toggleFullScreen={toggleFullScreen} />
}

showInline

Called just before the inline toolbar is positioned and displayed on the screen.

showInline(toolbar, context){
	console.log(toolbar, context)
}
render() {
	return <SunEditor showInline={showInline} />
}

showController

Called just after the controller is positioned and displayed on the screen.

showController(name, controllers){
	console.log(name, controllers)
}
render() {
	return <SunEditor showController={showController} />
}

Editor Language Object

You can translate the object below to any other language and pass it to the lang prop to set your locale language if it is not part of the strings of array above. Note: You will be aided by your editor's intellisense. Note If you are using an object like below, you need to make sure that you memoize it so that it doesn't run setOptions every time the editor re-renders. You can do this using useRef or useMemo

{
        code: 'en',
        toolbar: {
            default: 'Default',
            save: 'Save',
            font: 'Font',
            formats: 'Formats',
            fontSize: 'Size',
            bold: 'Bold',
            underline: 'Underline',
            italic: 'Italic',
            strike: 'Strike',
            subscript: 'Subscript',
            superscript: 'Superscript',
            removeFormat: 'Remove Format',
            fontColor: 'Font Color',
            hiliteColor: 'Highlight Color',
            indent: 'Indent',
            outdent: 'Outdent',
            align: 'Align',
            alignLeft: 'Align left',
            alignRight: 'Align right',
            alignCenter: 'Align center',
            alignJustify: 'Align justify',
            list: 'List',
            orderList: 'Ordered list',
            unorderList: 'Unordered list',
            horizontalRule: 'Horizontal line',
            hr_solid: 'Solid',
            hr_dotted: 'Dotted',
            hr_dashed: 'Dashed',
            table: 'Table',
            link: 'Link',
            math: 'Math',
            image: 'Image',
            video: 'Video',
            audio: 'Audio',
            fullScreen: 'Full screen',
            showBlocks: 'Show blocks',
            codeView: 'Code view',
            undo: 'Undo',
            redo: 'Redo',
            preview: 'Preview',
            print: 'print',
            tag_p: 'Paragraph',
            tag_div: 'Normal (DIV)',
            tag_h: 'Header',
            tag_blockquote: 'Quote',
            tag_pre: 'Code',
            template: 'Template',
            lineHeight: 'Line height',
            paragraphStyle: 'Paragraph style',
            textStyle: 'Text style',
            imageGallery: 'Image gallery',
	    dir_ltr: 'Left to right',
            dir_rtl: 'Right to left',
            mention: 'Mention'
        },
        dialogBox: {
            linkBox: {
                title: 'Insert Link',
                url: 'URL to link',
                text: 'Text to display',
                newWindowCheck: 'Open in new window',
                downloadLinkCheck: 'Download link',
                bookmark: 'Bookmark'
            },
            mathBox: {
                title: 'Math',
                inputLabel: 'Mathematical Notation',
                fontSizeLabel: 'Font Size',
                previewLabel: 'Preview'
            },
            imageBox: {
                title: 'Insert image',
                file: 'Select from files',
                url: 'Image URL',
                altText: 'Alternative text'
            },
            videoBox: {
                title: 'Insert Video',
                file: 'Select from files',
                url: 'Media embed URL, YouTube/Vimeo'
            },
            audioBox: {
                title: 'Insert Audio',
                file: 'Select from files',
                url: 'Audio URL'
            },
            browser: {
                tags: 'Tags',
                search: 'Search',
            },
            caption: 'Insert description',
            close: 'Close',
            submitButton: 'Submit',
            revertButton: 'Revert',
            proportion: 'Constrain proportions',
            basic: 'Basic',
            left: 'Left',
            right: 'Right',
            center: 'Center',
            width: 'Width',
            height: 'Height',
            size: 'Size',
            ratio: 'Ratio'
        },
        controller: {
            edit: 'Edit',
            unlink: 'Unlink',
            remove: 'Remove',
            insertRowAbove: 'Insert row above',
            insertRowBelow: 'Insert row below',
            deleteRow: 'Delete row',
            insertColumnBefore: 'Insert column before',
            insertColumnAfter: 'Insert column after',
            deleteColumn: 'Delete column',
            fixedColumnWidth: 'Fixed column width',
            resize100: 'Resize 100%',
            resize75: 'Resize 75%',
            resize50: 'Resize 50%',
            resize25: 'Resize 25%',
            autoSize: 'Auto size',
            mirrorHorizontal: 'Mirror, Horizontal',
            mirrorVertical: 'Mirror, Vertical',
            rotateLeft: 'Rotate left',
            rotateRight: 'Rotate right',
            maxSize: 'Max size',
            minSize: 'Min size',
            tableHeader: 'Table header',
            mergeCells: 'Merge cells',
            splitCells: 'Split Cells',
            HorizontalSplit: 'Horizontal split',
            VerticalSplit: 'Vertical split'
        },
        menu: {
            spaced: 'Spaced',
            bordered: 'Bordered',
            neon: 'Neon',
            translucent: 'Translucent',
            shadow: 'Shadow',
            code: 'Code'
        }
    }

Appreciation

Special Thanks to JiHong88 for the suneditor package.

Pull Requests

Pull requests are welcome

License

Suneditor React may be freely distributed under the MIT license.

suneditor-react's People

Contributors

adrian-jablonski1 avatar csbarnes avatar guido-visser avatar jihong88 avatar kristofferlund avatar mkhstar avatar rnielsen avatar serialine avatar shibukawa avatar tomaskovacikartin avatar wxjzeke avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar

suneditor-react's Issues

How can i handle the image base64 to server url?

I dont want the content image with base64, because its affect to database size too large,
So i wanna base64 to change server url.
I try react-quill but it's no module for set image size before image upload(submit).

Uncaught TypeError: this.src.renderToString is not a function

use:
import SunEditor, { katex } from 'suneditor-react';

setOptions={{
                    height: 200,
                    katex: { // Custom option
                        src: katex,
                        options: {
                            throwOnError: true,
                        }
                      },

result when work with math (just simple add 1 character to modal:

Uncaught TypeError: this.src.renderToString is not a function
    at Object.<anonymous> (main.js:1784)
    at Object._renderMathExp (main.js:1881)
(anonymous) @ main.js:1784
_renderMathExp @ main.js:1881

Cursor point is always pointing to first line

Hi all,
When ever i attached any image or added any content, always my mouse cursor is pointing to first line. Below i added my code, Kindly revert back to me

Thanks in advance

import React from 'react';
import './App.css';
import SunEditor from 'suneditor-react';
import 'suneditor/dist/css/suneditor.min.css';
import plugins from 'suneditor/src/plugins';

export default class App extends React.Component {

constructor(props) {
super();
this.state = {
content: ''
}

}

handleChange(data) {
this.setState({ content: data });
}

handleScroll(event){

}

handleClick(event){

}

handleKeyUp(event){

}

handleKeyDown(event){

}

handleDrop(event){
console.log("Drop : ");

}

handleImageUpload(targetImgElement, index, state, imageInfo, remainingFilesCount){

}

handlePaste(e, cleanData, maxCharCount){

}

render() {

return (
  <div className="App">
    <p> My Other Contents </p>
    <SunEditor
      width="100%"
      setContents={this.state.content}
      onChange={this.handleChange.bind(this)}
      onScroll={this.handleScroll.bind(this)}
      onClick={this.handleClick.bind(this)}
      OnKeyUp={this.handleKeyUp.bind(this)}
      OnKeyDown={this.handleKeyDown.bind(this)}
      onDrop={this.handleDrop.bind(this)}
      onImageUpload={this.handleImageUpload.bind(this)}
      setOptions={{
        plugins: plugins,
        buttonList: [
          ['font', 'fontSize', 'formatBlock'],
          ['paragraphStyle'],
          ['undo', 'redo'],
          ['bold', 'underline', 'italic', 'strike', 'subscript', 'superscript'],
          ['fontColor', 'hiliteColor', 'textStyle'],
          ['outdent', 'indent'],
          ['align', 'horizontalRule', 'list', 'lineHeight'],
          ['table', 'image'],
          ['fullScreen', 'showBlocks', 'codeView']
        ]
      }}
    />
  </div>
);

}
}

editor value

am tryint to set the initial content of the editor using

<SunEditor setContents={vendor_agreement} setOptions={{ height: 200, buttonList: buttonList.complex }} onChange={(content) => ( this.setVendorAgreement(content) )}></SunEditor>

but its showing blank yet vendor_agreement is not empty string

Parameter 'errorMessage' implicitly has an 'any' type.

Hi,

I just tried to add the editor based on the Readme's Getting Started section but I ran into this error with the typescript definition file.

C:/Codes/Repos/Common UI/Web/node_modules/suneditor-react/index.d.ts
(41,27): Parameter 'errorMessage' implicitly has an 'any' type.

I'm using the latest version, any idea how should I fix this?

Toolbar icons not show

Hello!

I try to use this library with a minimal configuration but when I tested, the result was a little strange:
Screenshot 2020-02-03 at 16 35 49
Somehow, the toolbar didn't show options' icons, only characters (but it works anyway).

My file only have this:

Screenshot 2020-02-05 at 12 42 10

Any idea?

Thanks,
Pedro

Unknown edit feature in disabled editor

Hello,

I amusing editor just for displaying content without ability to edit it.
Property disable is set to true .
When i go with my mouse just slightly over the top image this feature appears.
See attached screenshot.
What does it do ? Why is it shown in "disabled mode" ?

I should mention that i add that red image/logo to HTML string in backend based on business logic.
Also i couldnt manage to align the logo to the right even when I wrapped it in div and set text-align: right. When i inspected editor it somehow wrapped the image with <figure> element so that probably caused not aligning. I found out that suneditor completely ignores any element i wrap around img and it wraps it into own div and then figure element.

Inspecting editor in browser:
<div class="se-component se-image-container __se__float-none" contenteditable="false"><figure style="margin: 0px;"><img alt="logo" data-proportion="true" data-align="none" data-index="2" data-file-name="0nIb402rh8NCVV8FwLoffCw2f8Bl23zA2fzE74AAAAASUVORK5CYII=" data-file-size="0" data-origin="," data-size="," data-rotate="" data-rotatex="" data-rotatey="" data-percentage="auto,auto" style="" origin-size="133,55"></figure></div>

String i get from DB and set it in setContents:
<div style="text-align: right;"><img alt='logo' src='base64data'/></div>

unknown_feature_suneditor

suneditor-react version: 2.11.1

All events do not work

Hello,

First of all, thank you for your time and hard work on making this component.

I am using it to integrate SunEditor to my React App. However, it seems all your component's React events (onChange, onScroll, onClick, onKeyUp, onKeyDown, etc) do not work. I downloaded your source and tested right on it and all events does not work either

The following are from your file App.js (/example/src/App.js), I added handleChange just like you wrote on your document but it did not console.log the content

import React, { Component } from 'react'
import "suneditor/dist/css/suneditor.min.css";

import SunEditor from 'suneditor-react'


export default class App extends Component {
	handleChange(content){
	    console.log(content); //Get Content Inside Editor
	}

  render () {
    return (
      <div>
        <SunEditor onChange={this.handleChange} />
      </div>
    )
  }
}

Do you have any opinion on this matter or did I miss something here that make the events does not work?

Failed to create production build (UglifyJs Unexpected token)

Hi,

If I use 'npm start' suneditor works just fine for me.
However, if I try to create a production build I get the following error:

static/js/main.31f4794a.js from UglifyJs SyntaxError: Unexpected token: name (n) [./~/suneditor-react/dist/main.js:13,1199]

Any idea why?

React: 16.8.6
suneditor-react: 2.5.0

Uncaught TypeError: Cannot read property 'destroy' of undefined

Hi,

Thanks for package,

I have implemented the editor and when i set option buttonlist, getting following error.
Uncaught TypeError: Cannot read property 'destroy' of undefined

   <SunEditor setContents={this.state.emailbody}
            setOptions={{buttonList: buttonList.complex}}  

Adding name attribute to SunEditor React prop

I can't get any content value in my backend (Express) because there is no attribute name from the textarea/text input.

I tried add name attribute to the prop, like
<SunEditor name='content'/>

But still there is no such a "content" in my backend.

I was used Jodit Editor React before. I can easily add name attribute to the prop.
But in SunEditor, there is no actual textarea/text input with a name attribute if i really add a name prop.

ReferenceError: document is not defined

First of all: thanks, for the react adaptation for suneditor. It works great!

I'm using it on a Next.js application and just got a confusing situation:

When I access the page that uses the suneditor-react, it breaks when bundling due to a ReferenceError: document is not defined, even when using NoSsr.

Any idea on why is this happening?

Question: handling setContents and onChange

Hi, I noticed that many had similar questions on usage of setContents and onChange. I also noticed that in the documentation, you clearly stated that setContents and onChange must use different variables. My question is on 'how'. I would think something like that value={stateVariable} Then onChange={e =>setStateVariable(e)} should be available, but I guess that isn't.

Back to my question. I'm using a state variable to set initial value via setContents, which is obtained from browser's localStorage. Then inside of onChange, I need to update that variable as user types something. How do I achieve that when I can't use the same variable for setContents and modify it in onChange?
Thank you!

Style tag shown in editor

Hi,
thanks for the package,
I have implemented the editor as per the docs, but in editor shows the style tag,

import React from "react";
import SunEditor from 'suneditor-react';
import 'suneditor/dist/css/suneditor.min.css';

class Editor extends React.PureComponent {
constructor(){
super(props);
this.state={
content = `
   <!DOCTYPE html>
<html lang="en">
<head>
    <title></title>
    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width, initial-scale=1">
</head>
<style>
.textstyle{
padding: 20px;
text-align: center;
}
</style>
<body>
  <p class="textstyle">Test Content</p>
</body>
</html>
`
}
}

render(){
  return (
   <SunEditor setContents={this.state.content} />
 );
}

image

Auto focus problem

Hello! Im using suneditor on a form, and its starting with a auto focus on its fields.
My code:

import React from 'react';
import SunEditor from 'suneditor-react';
import PropTypes from 'prop-types';
import { Container } from './styles';

function SunEditorComponent({
    initialValue,
    onChange,
    onClickEditor,
    heightEditor,
    mode,
    placeHolder,
    ...rest
}) {
    return (
        <Container className="sun-editor-editable">
            <SunEditor
                {...rest}
                setContents={initialValue}
                onChange={onChange}
                lang="pt_br"
                onClick={onClickEditor}
                showToolbar={false}
                // show={false}
                autoFocus="false"
                // onImageUpload={handleImageUpload}
                setOptions={{
                    mode: 'inline',
                    buttonList: [
                        [
                            'undo',
                            'redo',
                            'font',
                            'fontSize',
                            'formatBlock',
                            'paragraphStyle',
                            'bold',
                            'underline',
                            'italic',
                            'strike',
                            'subscript',
                            'superscript',
                            'fontColor',
                            'hiliteColor',
                            'textStyle',
                            'removeFormat',
                            'outdent',
                            'indent',
                            'align',
                            'horizontalRule',
                            'list',
                            'lineHeight',
                            'table',
                            'link',
                            'image',
                            'video',
                            'fullScreen',
                            'showBlocks',
                            'codeView',
                            'print',
                            'save',
                        ],
                    ],
                }}
            />
        </Container>
    );
}

SunEditorComponent.propTypes = {
    initialValue: PropTypes.string.isRequired,
    mode: PropTypes.string,
    onChange: PropTypes.func,
    heightEditor: PropTypes.number,
    placeHolder: PropTypes.string,
};

SunEditorComponent.defaultProps = {
    heightEditor: null,
    onChange: null,
    mode: '',
    placeHolder: '',
};

export default SunEditorComponent;

And the one being called in the form

<SunEditorComponent
                        onChange={value =>
                            handleChange(value, 'courseDescription')
                        }
                        initialValue={courseDescription}
                        placeHolder="Edite aqui sua página de descrição no curso"
                        heightEditor={230}
                    />

Have a workaround to remove the autofocus from it?
image

Even if autoFocus is false suneditor receives focus for a moment and then looses it

I was expecting that sueditor would not receive focus if autoFocus is false.
However what actually happens is following:

  1. suneditor receives focus
  2. then it checks value of autoFocus
  3. if autofocus is false, suneditor blurs

This is particulary bad if I have long page (with scrolling) and suneditor instance is on the bottom - user is being automatically scrolled to suneditor.

Unfortunately I will have to most likely stop using this great library because of this bug.

Cannot use katex, Uncaught TypeError: Cannot read property 'open' of undefined

I am trying to use the katex plugin but clicking on the button throws the following error:

Uncaught TypeError: Cannot read property 'open' of undefined

options (passed via setOptions prop):

{
  width: '100%',
  height: 'auto',
  resizingBar: false,
  // I've also tried { src: window.katex } and { src: 'window.katex' }
  katex: 'window.katex',
  formats: ['p', 'blockquote', 'pre', 'h1', 'h2'],
  buttonList: [
    ['undo', 'redo'],
    ['formatBlock'],
    ['bold', 'italic', 'underline', 'strike', 'subscript', 'superscript'],
    ['list', 'indent', 'outdent'],
    ['link', 'image', 'math'],
    ['align'],
    ['removeFormat'],
  ],
}

What is the proper way to get the Katex/math plugin working?

Image setting does not work

Hi all,
First, many thank for wonderful editor.
I have issue with Image. Image setting buttons does not work for me.
Maybe I config wrong someth?
Thank you very much if you can help.
image

Edit link popup sometimes shows up on initial load

I am encountering a weird issue where the "Edit Link" popup sometimes shows up under the toolbar when navigating to a page with SunEditor.

image

The link text is from a breadcrumb on the page (the first link on the page).

This does not happen if you refresh on the page with the editor, only if you navigate from another page (we use react-router-dom) and even then it doesn't happen every time.

Not sure what is triggering it or how to go about debugging it.

How to get the text/content of a selection

Hello,
i am trying to implement "comment" functionality i should say.
When I highlight some text in editor with my mouse, then i want to click on the button which will add my custom component with text I highlighted in editor. Is it possible ? I couldnt find any editor method in documentation.

Hide and Show Toolbar with state

Thank you for this awesome library. I was looking around several options for editors , I find this one to fit my use case. But it is not clear to me how I can dynamically hide and show the toolbar / or the editor box.

I want to do like multiple section and put an edit button aside that my users can click to edit the section.
On disable state it should not show the toolbar and the box just the content.

Is this posible ?

TypeScript support

Hi!

I just noticed that SunEditor implemented TypeScript support. Ref: JiHong88/suneditor#287

Is this something that could be implemented in here as well?
When i import as referred to in the documentation: import SunEditor from "suneditor-react";, I get this error:
TS7016: Could not find a declaration file for module 'suneditor-react'.

It works if I surpress it, but with warnings.

Failed to load resource: net::ERR_INVALID_URL on setContents

Hi!

I'm using SunEditor(SE) on my React app. I'm saving content from SE to my database as Base64. When I'm getting it from data base and passing to editor via setContents everything works fine on Firefox but on other browsers I got "Failed to load resource: net::ERR_INVALID_URL " and images won't display.

When I try inspect html code of SE on broken browser I see html tag <img src="myImgBas64Code> and I can copy it and paste to browser and image is displaying correctly. So html tag is created via editor without errors .
<SunEditor ref={editorRef} disable={isReadOnly} showToolbar={!isReadOnly} onChange={handleChange} placeholder="Please type here..." setContents={scriptDescription} />

setContents에 markup string 삽입시 오류.

안녕하세요.
에디터 사용 중 아래와 같은 이슈가 있어 확인해주시면 좋을 것 같아 글 남깁니다 :)

에디터의 초기 컨텐츠 데이터 삽입을 위한 setContents props에
아래와 같은 형식의 문자열을 주입하면 destory 속성이 undefined라는 오류가 납니다.
이미지 태그가 있을시에 오류가 발생하는 것으로 추축되는데.. 확인해주시면 좋을 것 같아요!
그럼 수고하세요~

<p><img src="https://www.google.com/images/branding/googlelogo/2x/googlelogo_color_272x92dp.png" style="width: 900px;"><br></p>

Cannot read property 'destroy' of undefined
TypeError: Cannot read property 'destroy' of undefined

Updating the value of height in setOptions prop

Hi,

It appears that changes to setOptions aren't applied once the component is mounted. For example, if height is initially set to 250 and is then changed to 500, the height of the component stays at 250.

Loosing focus on initial typing in Internet Explorer 11

Hello, i am using suneditor-react package version 2.11.1.
When i want to type something to empty editor in Internet Explorer 11.3247 I click into editor area but then it immediately loses focus.
I have to be typing something and at the same time i have to click on editor to get some text in it or just click on editor and the be very quickly type something.
Once it has some value in it i can type more text, edit, etc. normally.

I am providing empty string from Redux to setContents property as a initial value.

Wordwrap problem for Persian letters

Hi, a problem I encountered, for Persian letters, when it reaches the end of the line, it goes from the middle of the word to the next line, is there a solution to this problem?
suneditor

plugin.fileTags[tag].toLowerCase is not a function When adding "Image" Or 'video' in buttonList

Hello,
I am using simple installation and trying to add Image and Video. but when I add 'Image' Or 'video'
in button list, I got this error
plugin.fileTags[tag].toLowerCase is not a function
and it crash the page, my editor configurations are simple

Import SunEditor, {buttonList} from 'suneditor-react';
import 'suneditor/dist/css/suneditor.min.css';

<SunEditor  setOptions={{  buttonList: [
		['image', 'fontSize', 'formatBlock', 'bold', 'underline', 'italic', 'strike', 'fontColor', 'hiliteColor', 'outdent', 'indent', 'align', 'horizontalRule', 'list', 'table', 'link', 'fullScreen', 'showBlocks', 'codeView'], ], }} 
onChange={this.onEditorChanges.bind(this)} setContents={this.state.content} />

am I missing something or Its known bug? Please help.

Issue with align and list buttonList options

Getting the following error while using list and align in buttonList.

align.js:83 Uncaught TypeError: this.util.changeElement is not a function
at Object.active (align.js:83)
at Object._applyTagEffects (main.js:15186)
at _onChange_historyStack (main.js:16309)
at pushStack (main.js:10630)
at Object.push (main.js:10651)
at Object.setContents (main.js:14563)
at Object.setContents (main.js:16683)
at SunEditor.componentDidUpdate (main.js:17168)
at commitLifeCycles (react-dom.development.js:19835)
at commitLayoutEffects (react-dom.development.js:22803)
at HTMLUnknownElement.callCallback (react-dom.development.js:188)
at Object.invokeGuardedCallbackDev (react-dom.development.js:237)
at invokeGuardedCallback (react-dom.development.js:292)
at commitRootImpl (react-dom.development.js:22541)
at unstable_runWithPriority (scheduler.development.js:653)
at runWithPriority$1 (react-dom.development.js:11039)
at commitRoot (react-dom.development.js:22381)
at finishSyncRender (react-dom.development.js:21807)
at performSyncWorkOnRoot (react-dom.development.js:21793)
at react-dom.development.js:11089
at unstable_runWithPriority (scheduler.development.js:653)
at runWithPriority$1 (react-dom.development.js:11039)
at flushSyncCallbackQueueImpl (react-dom.development.js:11084)
at flushSyncCallbackQueue (react-dom.development.js:11072)
at flushPassiveEffectsImpl (react-dom.development.js:22883)
at unstable_runWithPriority (scheduler.development.js:653)
at runWithPriority$1 (react-dom.development.js:11039)
at flushPassiveEffects (react-dom.development.js:22820)
at react-dom.development.js:22699
at workLoop (scheduler.development.js:597)
at flushWork (scheduler.development.js:552)
at MessagePort.performWorkUntilDeadline (scheduler.development.js:164)

TypeError Cannot read property 'style' of null

Hello, thanks for your work with with this it's appreciated.

Currently, I'm using sun editor to persist images in base64 to a database, but they are getting wrapped in a div with a class name of se-component which is causing an error TypeError Cannot read property 'style' of null. I've replicated it in this code sandbox https://codesandbox.io/s/setoptions-failed-with-cannot-read-property-style-of-null-4j8w6?file=/src/App.js By removing the se-compoent class it works just fine.

I'm not sure what I'm missing, is it intended that the <img tag is wrapped in a div with this class?

Thanks,

Doug

Issue with Alignment changes

Hi, I have encountered a problem while changing the alignment of text, we have changeElement method in utils but that was not in this.utils oject
image

image

insert image ( or text ) in the middle of content

I created a file manager that I can use to add photos to the editor by "appendContents" props

But instead of adding a photo at the end of the my content, I want my photo to be added in the last place where the cursor was focused (for example, In the middle of).

can you help me solve this problem?

cursor backs to beginning when `setContents` value change.

example:

const Editor = (props: {
  value: string
  onChange: (value: string) => void
}) => {
  const { value, onChange } = props

  return (
    <SunEditor
      setOptions={{ mode: 'balloon-always', minHeight: 'auto' }}
      setContents={value}
      onChange={onChange}
    />
  )
}

const App = () => {
  const [value, setValue] = useState('')
  return <Editor value={value} onChange={content => setValue(content)} />
}

every time I enter something , then the cursor back to start.

onChange the content and setContent rerender editor component

i use this editor and try to setContent from API data like this

<SunEditor onChange={this.onEditorChange} setContents={postState.content} setOptions={editorOptions} width="100%" lang="en" />

when the content change, component rerender with input line back to first line of editor,

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.