5
votes

We are building an editor and we would like to use TimyMCE and React for it. 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.

So, with TinyMCE and React, how do I add react component to the TinyMCE 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>);
    }
}

In the above code at "handleAddContent" I am trying to add <TemplateComp> to the editor, but it's get's rendered as [object] [Object]. I understand string concatenation does that. TinyMCE package being used - https://github.com/tinymce/tinymce-react.

But how do I add component to editor?

1
Have you figured it out?lukas

1 Answers

2
votes

Concatenating string with JSX expression (which in fact is javascript object tree of virtual nodes) in

prevState.content + <TemplateComp>Added Content</TemplateComp>

results in that you have described. You have to convert virtual DOM nodes to HTML, e.g. in following way:

prevState.content + ReactDOMServer.renderToStaticMarkup(<TemplateComp>Added Content</TemplateComp>)

this will work, albeit it is one way route how to statically render React component to Tiny MCE editor. If you really want to place React component with its lifecycle to rich text editor consider using Draft.js or a component based on it instead of Tiny MCE.