Botond Balogh
Botond Balogh

Reputation: 163

Include CKEditor5.css in iframe of React App

I implement CKEditor5 in a React web application created by CRA.

"@ckeditor/ckeditor5-react": "^9.0.0",
"react": "^18.3.1",

CKEditor works fine, and now I need to provide a preview of the content for users to double-check its appearance.

For the preview, I'm using an iframe to dynamically create HTML that mirrors the current document. However, I'm struggling to correctly reference the ckeditor5.css file within the iframe, which leads to styling inconsistencies between the editor and the preview.

Currently, my workaround is to manually copy the ckeditor5.css file to the public folder and reference it from there, but I'm not satisfied with this solution. Ideally, I want to reference the .css directly from node_modules.

useEffect(() => {
    if (!isEditing) {
      const previewData = () => {
        const iframe = iframeRef.current;
        if (iframe) {
          const html = `
            <!DOCTYPE html>
            <html>
              <head>
                <title>Preview</title>
              <style>
                @import url('ckeditor5.css'); <!--It works, if I put the .css into /public-->
                @import url('./node_modules/ckeditor5/dist/ckeditor5.css'); <!--How can I make this work?-->
                  body {
                    padding: 20px;
                  }
                </style>
              </head>
              <body class="formatted ck-content">
                ${contentToSave}
              </body>
            </html>
          `;
          iframe.contentWindow.document.open();
          iframe.contentWindow.document.write(html);
          iframe.contentWindow.document.close();
        }
      };
      previewData();
    }
  }, [contentToSave, isEditing]); 

Here’s a screenshot of the file structure from inspector sources showing the location of ckeditor5.css:

location of the ckeditor5.css

How can I refer to the ckeditor5.css from the screenshot so that I do not need to copy manually the .css into my public folder?

Upvotes: 0

Views: 59

Answers (0)

Related Questions