1

I am working with content editors (medium-editor specifically) that use contentEditable but are not in React. I have a use-case where someone can drag and drop images, or I can insert images. My question is instead of adding the following to the html of the editor:

editorHtml += '<img src ="something />'

I would ideally like to add a React component.

editorHtml += '<CoverImage src="something" />'

In other words, can React Components be added to contentEditable or innerHtml of html elements outside of React Components?

1 Answer 1

1

You have to render React Component to string.

To achieve this, use ReactDOMServer. To be precise, use its renderToString method. This outputs string with all fancy element attributes React needs (e.g. data-react-id). If you are after cleaner output, use renderToStaticMarkup instead.

Sign up to request clarification or add additional context in comments.

5 Comments

It should be noted that this will hand the markup to the editor, which will exit the React world again. The editor can do what it wants with it. That seems likely to cause lots of problems
Yes, this is one way road. From React world out. I cannot image what is reason behind this use case. Instead, OP should consider wrapping contentEditable into React component and control what happens.
thanks for the answer! The use-case is that I am using an editor that wasn't built in or for react, but inside of a react app. The intent was (1) not duplicate markup that has been setup in a component. (2) and more importantly, have that act as a React component and not just html markup. So instead of rendering the markup of a component via renderToString, is it possible to actually render the component and have it not exit the React world? (to @JoshDavidMiller's point). In other word, have it behave as a React component rather than just share its markup?
@geoboy I am not aware of any way to accomplish that, no. The two systems (React and medium-editor) have their own lifecycles and, more importantly, medium-editor is driven the DOM while React is driven by a virtual DOM. There would inevitably be clashing.
In React ecosystem, there is concept of portals. Portals render components to "other" container - whichever you pick. In this case, it could be contentEditable div (or any other element). E.g. Modals are perfect candidate for portals here - they are rendered to document.body. Not giving guarantees, give it a chance. Take a look at this npmjs.com/package/react-portal repo (or any similar one). Little theory here: joecritchley.svbtle.com/portals-in-reactjs

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.