Code Monkey home page Code Monkey logo

tinymce-react's Introduction

Official TinyMCE React component

About

This package is a thin wrapper around TinyMCE to make it easier to use in a React application.

Issues

Have you found an issue with tinymce-react or do you have a feature request? Open up an issue and let us know or submit a pull request. Note: For issues concerning TinyMCE please visit the TinyMCE repository.

tinymce-react's People

Contributors

alextkd avatar danieloakman avatar danoaky-tiny avatar dependabot[bot] avatar farzadhayat avatar fyrkant avatar gjulivan avatar gzzo avatar idooo avatar jscasca avatar lnewson avatar lwenn avatar olegwock avatar rkbhochalya avatar shanmen-tiny avatar simonfc avatar sirajalam049 avatar techtangents avatar tiny-james avatar tinydylan avatar tylerkelly13 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  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

tinymce-react's Issues

TinyMCE doesn't load in IE11

I've just embedded the <Editor /> component within my application and visited the demo (https://tinymce.github.io/tinymce-react/) and noticed that TinyMCE fails to load in IE11. It loads fine in Chrome, Firefox, Edge and Safari.

I'm currently using React 15.6.1 and rendering my Editor component like so:

<Editor
  init={tinymceConfig}
  initialValue={value}
  inline={false}
  onChange={handleChange}/>

It appears to be failing silently as there are no errors being logged to the console. Any ideas what could be causing this?

I'll do a little more digging when I get some more free time.

Unable to create multiple instances on same page

Hello,

My apologies, but I'm unable to find React-specific documentation for TinyMCE.

I'm trying to render two different instances of TinyMCE, but they seem to render the same initialValue no matter how many different ways I try to key them, add ids, etc:

<div>
     <div id="remote" className="remote">
         <h1>Changes on server: </h1>
            <Editor
                  key={1}
                  id={1}
                  className="remote"
                  initialValue={this.props.remoteconflict}
                  disabled={true} />
        </div>
         <br />
        <div id="local" className="local">
            <h1>Your changes: </h1>
             <Editor
                  key={2}
                  id={2}
                  className="local"
                  initialValue={this.state.localconflict}
                  onEditorChange={this.handleEditorChange}
                    }
                  }}
                />
              </div>
            </div>

Any ideas how I can get this to work?

Importing es6 in create-react-app: wrong URL.

I'm using create-react-app with this.

If I follow this guide: https://www.tiny.cloud/docs/integrations/react/ it works using:

<script src="https://cloud.tinymce.com/stable/tinymce.min.js"></script>

in my index.html.

But if I try to use https://www.tiny.cloud/docs/advanced/usage-with-module-loaders/#es2015modules working with Javascript imports it doesn't work anymore.

If I simply use this code as suggested:

import React, { Component } from "react";
import { Editor } from "@tinymce/tinymce-react";
// Import TinyMCE
import tinymce from 'tinymce/tinymce';
// A theme is also required
import 'tinymce/themes/modern/theme';

class App extends React.Component {
  handleEditorChange = (e) => {
    console.log('Content was updated:', e.target.getContent());
  }

  render() {
    return (
      <Editor
        initialValue="<p>This is the initial content of the editor</p>"
        init={{
          plugins: 'link image code',
          toolbar: 'undo redo | bold italic | alignleft aligncenter alignright | code'
        }}
        onChange={this.handleEditorChange}
      />
    );
  }
}

it try to load files from: http://localhost:4000/static/js/skins/lightgray/content.min.css.

But that link doesn't exists on my create-react-app server!

Here a reproduction: https://codesandbox.io/s/q3xzqxllkq

How to fix?

Update documentation to include custom plugin example

Overview

I am working on a react application and am using this wrapper to integrate tinymce as an editor. I have written a simple plugin that I would like to add to the editor.
The tinymce documentation shows how to include a custom plugin using the PluginManager.add function.

How do I add my custom plugin using this wrapper?

Skin false does not prevent loading of skins

What is the correct configuration with Create React App when loading resources yourself?

I get this so far:

import React from 'react';
import { Editor } from '@tinymce/tinymce-react';

import 'tinymce/tinymce';
import 'tinymce/themes/silver/theme';
import 'tinymce/skins/ui/oxide/skin.min.css'
import 'tinymce/skins/ui/oxide/content.min.css'
import 'tinymce/plugins/link';
import 'tinymce/plugins/code';

const RichTextEditor = () => {
  return (
    <Editor
      initialValue="<p>hello</p>"
      init={{
        skin=false,
        plugins: ['link', 'code'],
        toolbar: 'bold italic',
      }}
    />
  );
};

RichTextEditor.propTypes = {
  ...Editor.propTypes,
};

export default RichTextEditor;

But I still get

tinymce.js:5320 Resource interpreted as Stylesheet but transferred with MIME type text/html: "http://localhost:3000/static/js/skins/content/default/content.css".

Also there should be more clarification in documentation that modern theme is only for version 4 and you should use oxide with version 5, because in every part of the documentation, there is theme: modern and took me a while before I figured out that I should use oxide instead.

Use a placeholder

Hello, can you please tell me how to use placeholder with this Editor?
Thanks

Uncaught TypeError: Cannot read property 'getCore' of undefined

I am using tinymce/tinymce-react ^2.2.6
I am trying to implement 2 editors on a single page along with wiris plugins for maths and chemistry, but it's showing the error. Cannot read property 'getCore' of undefined. in editor_plugin.src.js.
Here is my code for two editors (JSX file)
import React, { Component } from 'react';
import {
Modal,
Button,
Grid,
Row,
Col,
ControlLabel,
FormControl,
FormGroup,
Radio
} from 'react-bootstrap';
import { DropdownButton, MenuItem } from 'react-bootstrap';
import PropTypes from 'prop-types';
import { Editor } from '@tinymce/tinymce-react';
import { withRouter } from 'react-router-dom';
import { connect } from 'react-redux';
import { loadTestData, saveTestData } from '../../../utils/localStorageUtil';

export default class TrueFlaseModalBody extends Component {
constructor(props) {
super(props);
this.state = {};
}
componentWillReceiveProps(nextProps) {
this.setState({
question: nextProps.editorQuestion ? nextProps.editorQuestion : '',
solution: nextProps.editorSolution ? nextProps.editorSolution : ''
})
}
componentDidMount() {
this.setState({
question: this.props.editorQuestion ? this.props.editorQuestion : '',
solution: this.props.editorSolution ? this.props.editorSolution : ''
})
// Editor.init({ setup: (editor) => console.log(editor)})
}
render() {
const {
handleQuestionChange,
handleSolutionChange,
editorQuestion,
editorSolution,
isCorrectHandle,
editorQuestionOptions,
changeQuestionType,
} = this.props;
return (
<React.Fragment>


<DropdownButton title="TRUE/FALSE" id={dropdown-basic-${1}}>
Multiple Choice Questions

True False




<Editor
cloudChannel="dev"
initialValue={editorQuestion}
menubar={true}
inline={true}
id='question'
value={this.state.question}
init={{
name: 'test' + +new Date(),
language: "en",
content_css: [
'https://***/tinyMce.css'
],
external_plugins: {
image: 'https://*****/tinymce/plugins/image/plugin.js',
tiny_mce_wiris:
'https://www.wiris.net/demo/plugins/tiny_mce/plugin.js'
},
plugins: [
'advlist autolink lists link charmap print preview anchor',
'searchreplace visualblocks code fullscreen',
'insertdatetime media table contextmenu paste imagetools wordcount'
],
file_browser_callback_types: 'image',
file_browser_callback: function(field_name, url, type, win) {
console.log(url, type, win);
win.document.getElementById(field_name).value =
'my browser value';
},
file_picker_type: 'image',
file_picker_callback: (cb, value, meta) => {
var input = document.createElement('input');
input.setAttribute('type', 'file');
input.setAttribute('accept', 'image/
');

          input.onchange = function() {
            var file = this.files[0];

            var reader = new FileReader();
            reader.onload = function() {
              var id = 'blobid' + new Date().getTime();
              var blobCache =
                window.tinymce.activeEditor.editorUpload.blobCache;
              var base64 = reader.result.split(',')[1];
              var blobInfo = blobCache.create(id, file, base64);
              blobCache.add(blobInfo);

              cb(blobInfo.blobUri(), { title: file.name });
            };
            reader.readAsDataURL(file);
          };

          input.click();
        },
        images_upload_handler: function (blobInfo, success, failure) {
          var xhr, formData;
          xhr = new XMLHttpRequest();
          xhr.withCredentials = false;
          xhr.open('POST', 'postAcceptor.php');
      
          xhr.onload = function() {
            var json;
      
            if (xhr.status != 200) {
              failure('HTTP Error: ' + xhr.status);
              return;
            }
      
            json = JSON.parse(xhr.responseText);
      
            if (!json || typeof json.location != 'string') {
              failure('Invalid JSON: ' + xhr.responseText);
              return;
            }
      
            success(json.location);
          };
      
          formData = new FormData();
          formData.append('file', blobInfo.blob(), blobInfo.filename());
      
          xhr.send(formData);
        },
        toolbar:
          'undo redo | styleselect | bold italic | alignleft aligncenter alignright alignjustify | bullist numlist outdent indent | link image | tiny_mce_wiris_formulaEditor | tiny_mce_wiris_formulaEditorChemistry'
      }}
      onChange={handleQuestionChange}
    />

    
   <FormGroup>
      {
        editorQuestionOptions.map((option, arrayIndex) => {
          return (
            < Row style={{ paddingBottom: "20px" }} >
              <Col lg={2}>
                <Radio id={arrayIndex} checked={option.isCorrect} onClick={isCorrectHandle} name="radioGroup" inline />
              </Col>
              <Col lg={9} style={{ position: 'relative', marginLeft: '-80px' }}>
                <FormControl value={option.name} />
              </Col>
            </ Row>
          )
        })
      }
    </FormGroup>
    <div id="options">
      <Editor
        cloudChannel="dev"
        name='solution'
        id='solution'
        value={this.state.solution}
        menubar={true}
        inline={true}
        init={{
          name: 'solution' + +new Date(),
          language: "en",
          content_css: [
            'https://s3.ap-south-1.amazonaws.com/test-portal-assets/tinyMce.css'
          ],
          external_plugins: {
            image: 'https://s3.ap-south-1.amazonaws.com/classplus-tinymce/tinymce/plugins/image/plugin.js',
            tiny_mce_wiris: 'https://www.wiris.net/demo/plugins/tiny_mce/plugin.js'
          },
          plugins: [
            'advlist autolink lists link charmap print preview anchor',
            'searchreplace visualblocks code fullscreen',
            'insertdatetime media table contextmenu paste imagetools wordcount'
          ],
          menubar: false,
          file_browser_callback_types: 'image',
          file_browser_callback: function(field_name, url, type, win) {
            console.log(url, type, win);
            win.document.getElementById(field_name).value =
              'my browser value';
          },
          file_picker_type: 'image',
          file_picker_callback: (cb, value, meta) => {
            console.log(">>>>>>>");
            var input = document.createElement('input');
            input.setAttribute('type', 'file');
            input.setAttribute('accept', 'image/*');

            input.onchange = function() {
              var file = this.files[0];

              var reader = new FileReader();
              reader.onload = function() {
                var id = 'blobid' + new Date().getTime();
                var blobCache =
                  window.tinymce.activeEditor.editorUpload.blobCache;
                var base64 = reader.result.split(',')[1];
                var blobInfo = blobCache.create(id, file, base64);
                blobCache.add(blobInfo);

                cb(blobInfo.blobUri(), { title: file.name });
              };
              reader.readAsDataURL(file);
            };

            input.click();
          },
          images_upload_handler: function (blobInfo, success, failure) {
            var xhr, formData;
        
            xhr = new XMLHttpRequest();
            xhr.withCredentials = false;
            xhr.open('POST', 'postAcceptor.php');
        
            xhr.onload = function() {
              var json;
        
              if (xhr.status != 200) {
                failure('HTTP Error: ' + xhr.status);
                return;
              }
        
              json = JSON.parse(xhr.responseText);
        
              if (!json || typeof json.location != 'string') {
                failure('Invalid JSON: ' + xhr.responseText);
                return;
              }
        
              success(json.location);
            };
        
            formData = new FormData();
            formData.append('file', blobInfo.blob(), blobInfo.filename());
        
            xhr.send(formData);
          },
          toolbar:
            'undo redo | styleselect | bold italic | alignleft aligncenter alignright alignjustify | bullist numlist outdent indent | link image | tiny_mce_wiris_formulaEditor | tiny_mce_wiris_formulaEditorChemistry'
        }}
        onChange={handleSolutionChange}
      />
    </div> 
    <Row>
      <Col lg={2}>
        <h4>TAGS</h4>
      </Col>
    </Row>
    <Row>
      <Col lg={12}>
        <FormControl placeholder="Enter your tags" />
      </Col>
    </Row>
  </React.Fragment>
);

}
}

Here is error:
editor_plugin.src.js:377 Uncaught TypeError: Cannot read property 'getCore' of undefined
at t.(anonymous function).t.(anonymous function).init (webpack:///./editor_plugin.src.js?:377:74)
at yx (tinymce.min.js:2)
at Array. (tinymce.min.js:2)
at Object.qt [as each] (tinymce.min.js:2)
at Ex (tinymce.min.js:2)
at Gx. (tinymce.min.js:2)
at Array. (tinymce.min.js:2)
at qt (tinymce.min.js:2)
at u (tinymce.min.js:2)
at n (tinymce.min.js:2)
at HTMLScriptElement.l.(anonymous function).l.(anonymous function).l.(anonymous function).o.onload (https://***/tinymce/tinymce.min.js:2:92230)

Init configuration only displays minimal features

This is how I'm initializing the component.

            <TinyMCE
                init={{
                    plugins: ['advlist autolink autosave lists link image charmap print preview hr anchor pagebreak',
                        'searchreplace wordcount visualblocks visualchars code fullscreen',
                        'insertdatetime media nonbreaking save table contextmenu directionality',
                        'emoticons template paste textcolor colorpicker textpattern imagetools codesample toc help'],
                    toolbar1: 'undo redo | insert | styleselect | bold italic | alignleft aligncenter alignright alignjustify | bullist numlist outdent indent | link image',
                    toolbar2: 'print preview media | forecolor backcolor emoticons | codesample help',
                    image_advtab: true,
                    file_browser_callback_types: 'image',
                    file_picker_callback: filePickerCallback,
                    branding: false,
                    height: 400,
                }}
                initialValue={this.props.content}
                onChange={(e) => handleEditorChange(e, this.props)}
            />

This is what the output looks like:
8zhdry

This is what it looks like when I use react-tinymce:

screen shot 2017-11-27 at 09 10 22

Not sure what I'm doing incorrectly. Help would be appreciated.

Cannot read property 'unbind' of undefined

I installed "@tinymce/tinymce-react": "^2.3.0",
I wrote my own component following the documentation

import React from "react";
import { connect } from "react-redux";

import { Editor } from "@tinymce/tinymce-react";

/**Actions */
import { editorOnChange } from "../../../actions";

class CKEditor extends React.Component {
  handleEditorChange = (content) => {
    const {
      id,
      editorOnChange,
      reducer: { actionType },
    } = this.props;
    editorOnChange(actionType, id, content);
  };

  render() {
    return (
      <Editor
        apiKey="8g8nxiiua9o6rxmlgdkupdq0cwtn4ws1819v8typvr8opxb0"
        init={{
          plugins:"powerpaste",
          toolbar:
            "formatselect | paste | bold italic strikethrough forecolor backcolor | link | alignleft aligncenter alignright alignjustify  | numlist bullist outdent indent  | removeformat | fontselect | fontsizeselect",
          font_formats:
            "Andale Mono=andale mono,times;Arial=arial,helvetica,sans-serif;Arial Black=arial black,avant garde;Comic Sans MS=comic sans ms,sans-serif;Courier New=courier new,courier;Helvetica=helvetica;Tahoma=tahoma,arial,helvetica,sans-serif;Terminal=terminal,monaco;Times New Roman=times new roman,times;Trebuchet MS=trebuchet ms,geneva;Verdana=verdana,geneva;Webdings=webdings;Wingdings=wingdings,zapf dingbats;Akzidenz-Grotesk Std=Akzidenz-Grotesk Std",
        }}
        value={this.props.value}
        onEditorChange={this.handleEditorChange}
      />
    );
  }
}

const mapDispatchToProps = {
  editorOnChange,
};

export default connect(
  null,
  mapDispatchToProps,
)(CKEditor);

I use this component at least at 3 different pages. When i'm load this component at first, it's all ok, no crashes, but when i want to change page to another, where editor component is use too, i have a crash and error at console

Uncaught TypeError: Cannot read property 'unbind' of undefined
    at Yx.<anonymous> (tinymce.min.js?apiKey=0vljbszrz9brsvptl0vgtuitgk4b8rt3wc0c65kj49nmvuz7:76)
    at Jg.c.fire (tinymce.min.js?apiKey=0vljbszrz9brsvptl0vgtuitgk4b8rt3wc0c65kj49nmvuz7:8)
    at Yx.fire (tinymce.min.js?apiKey=0vljbszrz9brsvptl0vgtuitgk4b8rt3wc0c65kj49nmvuz7:8)
    at rp (tinymce.min.js?apiKey=0vljbszrz9brsvptl0vgtuitgk4b8rt3wc0c65kj49nmvuz7:8)
    at qx (tinymce.min.js?apiKey=0vljbszrz9brsvptl0vgtuitgk4b8rt3wc0c65kj49nmvuz7:8)
    at Yx.remove (tinymce.min.js?apiKey=0vljbszrz9brsvptl0vgtuitgk4b8rt3wc0c65kj49nmvuz7:8)
    at Object.remove (tinymce.min.js?apiKey=0vljbszrz9brsvptl0vgtuitgk4b8rt3wc0c65kj49nmvuz7:8)
    at Editor.componentWillUnmount (Editor.js:71)
    at callComponentWillUnmountWithTimer (react-dom.development.js:14280)
    at HTMLUnknownElement.callCallback (react-dom.development.js:100)

It only happens when there is plugins property available. If i remove it, everything works good
Version of Tiny - "@tinymce/tinymce-react": "^2.3.0",

I updated api key to premium, but the problem has not disappeared

Multiple instances with different configuration

Hi, it seems that React version has a problem with multiple instances - when the settings are the same, then it's alright, but once I try to set, for example "fixed_toolbar_container", all instances follow setting of the last one.

How do I autofocus the element?

I'd like to autofocus the editor at certain times. Is there way to do this? The docs use:

    auto_focus : "elm1"

but I don't think I have access to the original ID of the element when tinymce-react is creating it, do I?

Uncaught TypeError: Cannot read property 'remove' of null

I have a issue :
Uncaught TypeError: Cannot read property 'remove' of null
at Editor.componentWillUnmount (Editor.js:71)
at callComponentWillUnmountWithTimer (react-dom.development.js:8732)
at HTMLUnknownElement.callCallback (react-dom.development.js:542)

getTinymce() can sometimes return nulls in componentWillUnmount()

getTinymce().remove(this.editor);

It seems that it occurs when tinymce is not loaded yet.

Tks for your good work !

Cant see the plugins at all. Just the textarea is visible.

<Editor
                      inline={false}
                      init={{
                          plugins: 'link image code',
                          toolbar: 'undo redo | bold italic | alignleft aligncenter alignright | code'
                      }}
                      initialValue={this.state.mailBody}
                      onChange={this.handleChange}
                    />

Cant see the plugins at all. Just the textarea is visible.

Loading external plugins from local machine

Hi i had a plugin in my local machine and i try to integration it in existing build using the following code

external_plugins: {
    'eqneditor':'file:///Users/varun.meka/Desktop/tiny_mce_v3.5.8⁩/plugins⁩/equation⁩/editor_plugin.js'
  },

but it's not loading

can not get editor references when Multiple tinymce on the same page

I need to get editor reference since i am trying to implement wordpress like image insert feature, where image insert code will be owned by me and I will use the command
editorRef.insertContent('<a href="${image_url}">document</a>');

But when I have multiple instances of tinymce i am not able to get editorRef correctly.
Here is my code

import React from 'react';
import { Editor } from '@tinymce/tinymce-react';

class CustomWisivigComponent extends React.Component {
    constructor(props) {
        super(props);
        this.putWisivigRef = this.putWisivigRef.bind(this);
        this.returnCmp = <Editor
            apiKey={"myKey"}
            init={{
                setup: (editor) => this.putWisivigRef(editor),
                height: 700,
                plugins: 'image table link code',
                selector: "textarea",  // change this value according to your HTML
                default_link_target: "_blank"

            }}
            initialValue={this.props.value}
            onEditorChange={(event) => {
                this.props.onChange(event)
            }}
        />
    }

    putWisivigRef(ref) {
        console.log("setting editorRef to "+ref.id + " in component with props="+JSON.stringify(this.props))
        this.setState({editorRef: ref})
    }

    onImageInsert(propd) {
        console.log(this.state.editorRef)
    }

    render() {

        return (
            <div>
                {this.returnCmp}
            </div>
        );

    }
}

export default CustomWisivigComponent;

And I am trying to render it like this

<CustomWisivigComponent id="1"/>
  <CustomWisivigComponent id="2"/>

The problem is when i execute the code putWisivigRef is called with two references but the context of this is missed and always the putWisivigRef of first component is called. And hence when I try to insert something in the first component, it gets inserted into second (since first one's reference gets overridden) and when I try to insert in 2nd it results into null pointer, since it was never called. I tried passing this from the setup: (editor) => this.putWisivigRef(editor) as well but that too did not work.

when we render the above form it logs

screen shot 2018-12-30 at 3 09 48 pm

but ideally it should have been

setting editorRef to tiny-react_10038262721546162755458 in component with props={"id":"1"}
setting editorRef to tiny-react_19726510231546162755460 in component with props={"id":"2"}

TinyMCE & React Router Dom incompatible?

I have following issue,:
Scenario 1: when I go from my main screen '/' to the screen with editor '/editor' and start typing something then press 'back button' in browser I lose all my state data and I get an error from react-router-dom:
Uncaught TypeError: Cannot read property 'getSelection' of null.
Even if I see previous page nothing is rendered on it. And from react developer tools I see that route get stack on the '/editor'.

Scenario 2: when I go from my main screen to the screen with editor and start typing something then press somewhere outside of editor then 'back button' in browser everything works great.

Seems that iframe brake React Browsing History. Any thoughts on this issue?

Solution:
Fixed in version 16.5.2 of React as per issue #13650

document base url does not update when URL changes in a single-page-app?

I discovered a bug in my app that uses tinymce-react, related to the handling of relative URLs. I'm not certain, but I'm guessing that it's related to how document_base_url is handled.

Here's how I've observed the bug:

  • Page loads with a url like dashboard.wikiedu.org/courses/My_School/My_course_(Fall_2018)
  • User navigates to dashboard.wikiedu.org/courses/My_School/My_course_(Fall_2018)/timeline
  • TinyMCE field contains a link like /training/students/getting-started.
  • After saving, the now-relative updated url is one level off of what it originally was.

In contrast, the relative url is still pointed to the correct place after saving if the user loads dashboard.wikiedu.org/courses/My_School/My_course_(Fall_2018)/timeline initially.

Option to not set content to initialValue on load

When content is already in the html the initialValue over writes the content. Having an option to not do this would be ideal.

One suggestion is if initialValue is null than don't set the content.

Add React Component to the Editor

We have scenarios where on an event we have to add template based content to the Editor. I am planning to design the templates as React component.

how do I add react component to the editor?

Below is the controlled component I created. 'handleAddContent' does the work of adding a component into the editor

export class AppEditor extends React.Component<iEditorProps, iEditorState> {

    innerEditor: React.RefObject<Editor>;

    constructor(props: iEditorProps) {
        super(props);
        this.state = {
            content: ''            
        };
        this.innerEditor = React.createRef();
    }


    handleChange = (content) => {
        this.setState({ content });
    }

    handleAddContent = (e) => {
        this.setState(prevState => {
            return { content: prevState.content + <TemplateComp>Added Content</TemplateComp> }
        });
    }

    render() {
        return (
            <div>
                <Editor ref={this.innerEditor} inline onEditorChange={this.handleChange} value={this.state.content} />
            </div>);
    }
}

I am trying to add to the editor, but it's get's rendered as [object] [Object], I see it's because of the string concatenation. But then how can i add component content to the editor?

Get instance of Multiple editors in react

I have two instances of react editor on my page. i want to insert image in them independently. I am creating my react widget like this

class CustomWisivigComponent extends React.Component {
    constructor(props) {
        super(props);
        this.onImageInsert = this.onImageInsert.bind(this);
        this.returnCmp = <Editor
            apiKey={"mypreciousKey"}
            init={{
                setup: (editor) => this.setState({editorRef: editor}),
                height: 700,
                plugins: 'image table link code',
                selector: "textarea",  // change this value according to your HTML
                default_link_target: "_blank"

            }}
        />
    }
//this is called from other components
    onImageInsert(propd) {
        //TODO fix the height and width.
        if(propd.fileType && propd.fileType == 'Image') {
            this.state.editorRef.insertContent('<img alt="Smiley face" height="${height}" width="${width}" src="${image_url}"/>'.replace("${image_url}",propd.AssetIdentifiers.callbackUrl).replace("${width}",propd.dimension.width).replace("${height}",propd.dimension.height));
        } else {
            this.state.editorRef.insertContent('<a href="${image_url}">document</a>'.replace("${image_url}",propd.AssetIdentifiers.callbackUrl));

        }
    }

    render() {
        return (
            <div>
                    {this.returnCmp}
            </div>
        );

    }
}

But this.state.editorRef.insertContent  will always insert image in the last wisiwig of the page instead of whichever is active. Am i missing anything?

Problem with page integrations/react.md

affected page: https://www.tinymce.com/docs/integrations/react/

Could you please add a mechanism that doesn't use your server in a blocking fashion? Either how to use the tinymce npm module, or how to load tinymce asynchronously (bonus points if I can render a textarea while waiting for tinymce to load).

I tried to implement the latter, but somehow using this to inject the script caused it to be window.tinyMCE instead of window.tinymce and so tinymce-react didn't find it.

On Blur event not supported

I would like capture the content only after user completes the edit operation. so please add the onBlur event support.

ReactJS Editor wont render JavaScript content

Hi All,

I have project that I am working on, and part of it is a plugin / javascript editor.
The tinyMCE container never renders the value!
I've had to move this project to a private repo.

But here it the public version before:
https://github.com/WinWinHost/mqtt-data-generator

Basically this is a MERN project and in the FormAlgorithms.js component I am NOT able to render and edit JavaScript. There is no error displayed or reason given. Just a blank TinyMCE.

But the tinyMCE area always remains blank, even though on the console I can see the content is being retrieved correctly.

Here is the JS, which is rendering a blank TinyMCE.

      <Editor 
          content={this.state.fileContents}
          config={{
            plugins: 'autolink link image lists print preview',
            toolbar: 'undo redo | bold italic | alignleft aligncenter alignright'
          }}
          onChange={this.handleInputChange}
        />

And here is the output of this.state.fileContents:

'use strict';

const autoregressive = (previousObservation, currentSensorObservations, algorithmConfig) => { // jshint ignore: line
  return {
    value: previousObservation ? previousObservation.value : undefined
  };
};

module.exports = autoregressive; 

Thanks in Advance for your help.

-Robert Baindourov

Editor sends a request per each created instance

I have a page with dynamic number of editors, they may appear or be destroyed. After editor created it sends a request with apiKey. I have a case, when there are like 60+ editors on a page and each sends a request. How could I reduce number of requests? CSS files are requested each time for each instance too.

selection_077
selection_076

Disabled false/true on the fly

Hi there,

I am passing disabled true, then false, then true, when trying to do some functionality, unfortunately, it is not updating the editor, even if I send the correct disabled true or false after the first init. Is there anyway to fix this or a workaround?

Thanks

EDIT: This happens in the first instance of init, in a few ms when the app is loading, redux sends disabled true, and then false, and it remains on true for some reason. Happens 50% of the time, even if the props are coming correct.

Error with initial setup

I have the script tag in the head and have imported and tried to use the component like so

<Editor
        value="<p>This is the initial content of the editor</p>"
        config={{
          plugins: 'link image code',
          toolbar: 'undo redo | bold italic | alignleft aligncenter alignright | code'
        }}
        onChange={(e) => console.log('comeone')}
/>

This is the error I receive in the console.

Uncaught TypeError: Cannot read property 'length' of undefined
    at Editor.setContent (tinymce.js:40536)
    at Editor.eval (Editor.js:51)
    at Dispatcher.fire (tinymce.js:23089)
    at Editor.fire (tinymce.js:23329)
    at initEditor (tinymce.js:38400)
    at tinymce.js:38551
    at tinymce.js:8781
    at tinymce.js:8249

how to update the initialValue?

thank you for providing such a great react implementation!
And how to update the data(initialValue) when the editor has instantiated?

Example on CodeMirror?

To more easily play with the integration, it would be great to be able to see the example running on CodeMirror or similar.

How to get tinyymce instance?

tinymce.activeEditor.uploadImages(function(success) {
  document.forms[0].submit();
});

I need to call the above code.

Cannot read property 'unbind' of undefined

I installed "@tinymce/tinymce-react": "^2.3.0",
I wrote my own component following the documentation

import React from "react";
import { connect } from "react-redux";

import { Editor } from "@tinymce/tinymce-react";

/**Actions */
import { editorOnChange } from "../../../actions";

class CKEditor extends React.Component {
  handleEditorChange = (content) => {
    const {
      id,
      editorOnChange,
      reducer: { actionType },
    } = this.props;
    editorOnChange(actionType, id, content);
  };

  render() {
    return (
      <Editor
        apiKey="8g8nxiiua9o6rxmlgdkupdq0cwtn4ws1819v8typvr8opxb0"
        init={{
          plugins:"powerpaste",
          toolbar:
            "formatselect | paste | bold italic strikethrough forecolor backcolor | link | alignleft aligncenter alignright alignjustify  | numlist bullist outdent indent  | removeformat | fontselect | fontsizeselect",
          font_formats:
            "Andale Mono=andale mono,times;Arial=arial,helvetica,sans-serif;Arial Black=arial black,avant garde;Comic Sans MS=comic sans ms,sans-serif;Courier New=courier new,courier;Helvetica=helvetica;Tahoma=tahoma,arial,helvetica,sans-serif;Terminal=terminal,monaco;Times New Roman=times new roman,times;Trebuchet MS=trebuchet ms,geneva;Verdana=verdana,geneva;Webdings=webdings;Wingdings=wingdings,zapf dingbats;Akzidenz-Grotesk Std=Akzidenz-Grotesk Std",
        }}
        value={this.props.value}
        onEditorChange={this.handleEditorChange}
      />
    );
  }
}

const mapDispatchToProps = {
  editorOnChange,
};

export default connect(
  null,
  mapDispatchToProps,
)(CKEditor);

I use this component at least at 3 different pages. When i'm load this component at first, it's all ok, no crashes, but when i want to change page to another, where editor component is use too, i have a crash and error at console

Uncaught TypeError: Cannot read property 'unbind' of undefined
    at Yx.<anonymous> (tinymce.min.js?apiKey=8g8nxiiua9o6rxmlgdkupdq0cwtn4ws1819v8typvr8opxb0:76)
    at Jg.c.fire (tinymce.min.js?apiKey=8g8nxiiua9o6rxmlgdkupdq0cwtn4ws1819v8typvr8opxb0:8)
    at Yx.fire (tinymce.min.js?apiKey=8g8nxiiua9o6rxmlgdkupdq0cwtn4ws1819v8typvr8opxb0:8)
    at rp (tinymce.min.js?apiKey=8g8nxiiua9o6rxmlgdkupdq0cwtn4ws1819v8typvr8opxb0:8)
    at qx (tinymce.min.js?apiKey=8g8nxiiua9o6rxmlgdkupdq0cwtn4ws1819v8typvr8opxb0:8)
    at Yx.remove (tinymce.min.js?apiKey=8g8nxiiua9o6rxmlgdkupdq0cwtn4ws1819v8typvr8opxb0:8)
    at Object.remove (tinymce.min.js?apiKey=8g8nxiiua9o6rxmlgdkupdq0cwtn4ws1819v8typvr8opxb0:8)
    at Editor.componentWillUnmount (Editor.js:71)
    at callComponentWillUnmountWithTimer (react-dom.development.js:14280)
    at HTMLUnknownElement.callCallback (react-dom.development.js:100)

It only happens when there is plugins property available. If i remove it, everything works good
Version of Tiny - "@tinymce/tinymce-react": "^2.3.0",

TinyMCE-React not initializing until second load

Hello! I'm having an issue loading tinymce.

I have a Editor instance that's inside a higher order component, that's loaded when the user clicks the 'edit' button. The first time this happens, it looks like the 'init' action is not passed to the setup function. If the user goes back, and then click the button, then the init action is dispatched and tinymce loads as expected.

Here's a gif of the issue in action: http://g.recordit.co/x7XR89TcIJ.gif

Additional notes: I'm on 2.2.5.

Injected editor is non-responsive sometimes when dragging inside SharePoint modern page

Hi!
I injected tinymce-react into my SPFx webpart, it works, but there're really annoying small issues:
If drag and drop the webpart to different places in the layout 2 times, the editor hides its content, the editor is blank (the body of iframe is empty in html) and it's impossible to edit content until i reload the page. After i reload the page the old content is there.
Also if at first time i want to edit text inside the editor, cursor jumps into the beginning of the line. So for example there was text "Not finished" and i click inside the editor to add words after "finished", cursor is in correct position in the end of the line, but i start typing " yet" and it goes to the start and I get " yet Not finished" as the result.

The editor is initialized like this:

<Editor
        id={id}
        init={{
          plugins: ['paste', 'link', 'insertdatetime image'],
          skin_url: `${rootUrl}/SiteAssets/`,
          inline: false,
          menubar: false
        }}
        currentContent={content}
        onChange={(event) => {
          this.updateEditorContent(event.target.getContent());
        }}
      />

tinymce/[email protected]
[email protected]

Rendering tinymce content without editor

I want to render tinymce content just for view for specific set of users. I am creating a list which looks fine in editor but when rendering as plain html the spacing is not correct.

I am using the below configuration,

{ resize: false, height: 200, menubar: false, plugins: 'lists', toolbar: 'undo redo | styleselect | bold alignleft aligncenter alignright | bullist numlist outdent indent ', selector: 'textarea' }

Attaching the screenshots for reference,
i1
i2

Any reason why react & react-dom are direct dependencies of the app?

Any reason why react & react-dom are direct dependencies of the app? instead of specifying a range of peer dependencies or explicitly mention in the docs that you need specific version?

Because any project using this package is 100% using react. So, if you specify it as a peer dependencies with a range or explicitly mention in the readme or changelog or something the minimum version required it will be better than having two version of react in your bundle.

initialValue will overwrite newer set value

The content of the Editor is loaded asynchronously, but I wanted to render the Editor itself already, because it takes quite some time. Problem is, that when changing the "value" attribute between the initial mounting and the final init of the editor, it will be overwritten by the "init" callback:

in src/components/Editor.tsx:

editor.on('init', () => {
  this.initEditor(editor, initialValue);
});

I think the solution would be to guess the initialValue in the "initEditor" function instead of giving it here as an parameter.

Integrate NYTimes/Ice external plugin

Hello. I'm interested in using this 3rd party plugin: NYTimes/Ice, for track changes. I'm not sure how to integrate it, however.

Their documentation says:

Tinymce initialization - Add the ice plugin to your tinymce plugins directory and include the following in your tinymce init:

      tinymce.init({
        plugins: 'ice',
        theme_advanced_buttons1: 'ice_togglechanges,ice_toggleshowchanges,iceacceptall,icerejectall,iceaccept,icereject',
        ice: {
          user: { name: 'Miss T', id: 1},
          preserveOnPaste: 'p,a[href],i,em,strong',
          // Optional param - defaults to the css found in the plugin directory
          css: 'http://example.com/custom.css'
        },
        ...
      });

However, there is no plugins folder, so I don't know where I would place the plugin. Is this even possible right now?

Cannot disable autofocus

Hello and thanks for a great component.

I am having trouble disabling autofocus. Here is what I tried so far:

<Editor init={{auto_focus: false, ... }} ... />

and also

<Editor init={{auto_focus: '', ... }} ... />

But neither of them works. Whenever I navigate to a page with the Editor, it gets focus.

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.