3

I am trying to highlight some javascript code using PrismJS but the text i entered does not change color at all. I have tried using the CDN for prismjs and also npm but i don't see any change when i use Prism.highlightAll(). Here is the editor component code:

import React, {useEffect,useState} from 'react';
import Prism from 'prismjs';

import './editor.css';

const Editor = (props) => {
    const [content, setContent] = useState(props.content);

    useEffect(() => {
    console.log(content);
    Prism.highlightAll();
    }, [props.language, content]);

    return (
      <div className="code-edit-container">
        <textarea
          className="code-input"
          value={content}
          onChange={evt => setContent(evt.target.value)}
        />
        <pre className="code-output">
          <code className={'language-javascript'}>{content}</code>
        </pre>
      </div>
    );
  };

  export default function CodeEditor() {
    const [editorLanguage, setEditorLanguage] = useState("javascript");
    return (
      <div className="CodeEditor">
        <fieldset>
          <input
            type="radio"
            id="javascript"
            name="language"
            value="javascript"
            checked={editorLanguage === "javascript"}
            onChange={() => setEditorLanguage("javascript")}
          />
          <label htmlFor="javascript">JavaScript</label>
        </fieldset>

        <Editor language={editorLanguage} />
      </div>
    );
  }
vishnkr
  • 67
  • 1
  • 9

1 Answers1

1

I tried your Editor component code and it worked for me. One thing I noticed is that you're not using the props.language object to set the language for prism from the codeEditor component. Your className is indicating that you're only using javascript as a language for Prism so it will only parse and beautify javascript. so change your className to using className={props.language} intead of className={'language-javascript'}.