Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

code block not displaying when previewing in react-quill

In this code, I am trying to insert a code block using react-quilljs

import React, { useState } from 'react';
import hljs from 'highlight.js';

import { useQuill } from 'react-quilljs';

import 'quill/dist/quill.snow.css'; // Add css for snow theme

export default () => {

  hljs.configure({
    languages: ['javascript', 'ruby', 'python', 'rust'],
  });

  const theme = 'snow';

  const modules = {
    toolbar: [['code-block']],
    syntax: {
      highlight: (text) => hljs.highlightAuto(text).value,
    },
   
  };

  const placeholder = 'Compose an epic...';

  const formats = ['code-block'];

  const { quill, quillRef } = useQuill({
    theme,
    modules,
    formats,
    placeholder,
  });
  

  const [content, setContent] = useState('');

  React.useEffect(() => {
    if (quill) {
      quill.on('text-change', () => {
        setContent(quill.root.innerHTML);
      });
    }
  }, [quill]);

  const submitHandler = (e) => {};

  return (
    <div style={{ width: 500, height: 300 }}>
      <div ref={quillRef} />

      <form onSubmit={submitHandler}>
        <button type='submit'>Submit</button>
      </form>
      {quill && (
        <div
          className='ql-editor'
          dangerouslySetInnerHTML={{ __html: content }}
        />
      )}
    </div>
  );
};

Using the above code, I get the following preview of the editor's content

enter image description here

There are two problems with this:

  1. There is no code syntax highlighting, as I want to achieve this using the highlihgt.js package, inside the code block inside the editor, and

  2. The code block is not displayed (with the black background and highlighting syntax when it's working) in the previewing div outside the editor.

How can I fix these two issues?

like image 819
BlackMath Avatar asked Dec 12 '25 12:12

BlackMath


1 Answers

Look at the css in the editor mode. It depends on two class names ql-snow and ql-editor. You can fix this issue by wrapping it around one more div with className ql-snow.

<div className='ql-snow'> 
   <div className='ql-editor' dangerouslySetInnerHTML={{ __html: content }}> 
   <div/> 
</div>

This should work.

like image 58
Krish Avatar answered Dec 15 '25 05:12

Krish



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!