Search code examples
javascripthtmlreactjsnext.jsprismjs

How to auto-indent code string in PrismJS? NextJs APP


i am trying to use PrimsJs in a react project, my objetive is create a static template page, and add snippets, i am not sure if is the best option(primsjs) but i am trying to auto-indent the code, because actually my code is rendered in one line


enter image description here

THIS IS MY PAGE

import { MainLayout } from "../components/layouts/MainLayout";
import { Hero1, Hero1Code} from "../theme/blocks/hero/Hero1";

export default function Home() {
    return (
        <MainLayout>
            <h1>Home Page</h1>
            <Hero1 />
            <Hero1Code />
        </MainLayout>
    );
}

THIS IS MY PRIMSJS COMPONENT

import React, { useEffect } from "react";
import Prism from "prismjs";
import "prismjs/themes/prism-tomorrow.css";


export default function Code({ code, language }) {
  useEffect(() => {
    Prism.highlightAll();
  }, []);

  return (
    <div className="Code">
      <pre>
        <code className={`language-${language}`}>{code}</code>
      </pre>
    </div>
  );
}

THIS IS MY COMPONENT

import React from "react";

import { renderToString } from "react-dom/server";
import Code from "../../../components/prism/code";

export const Hero1 = () => {
    return (
        <section className="wrapper bg-light">
           ...
        </section>

    );
};

export const Hero1Code = () => {
    const content = renderToString(<Hero1/>);
    return (
        <>
            <div className="App">
                <Code code={content} language="html" />
            </div>
        </>
    );
};

Any help will be very welcome, also i am open to try other package


Solution

  • I don't think that PrismJS has such an option, in my opinion it would be best to just indent the code string before passing it to the <Code /> component.

    You could use this library: https://github.com/zebzhao/indent.js

    Import it:

    import indent from 'indent.js';
    

    And indent the code like this:

    const content = indent.html(renderToString(<Hero1/>));
    

    However, looking at your screenshot code example, I can see that you have a lot of divs smashed into one line. In this case, indentation would not really help, as it takes care of the relations between separate lines.

    You could take a look at using a library like this, which seems to split code into separate lines.

    https://www.npmjs.com/package/pretty