How to prettify dynamic code snippets in React?

4.2k views Asked by At

I've looked into code prettifiers like google-code-prettify, beautify, etc. Unfortunately, I haven't been able to get any of these to work in my React app. I am currently using react-ace to display dynamically populated code snippets, but they are only color-highlighted, not formatted.

Are there any simple examples of some way that I can get this to work in a React App? It doesn't have to be using Ace editor - that was sort of my hack to get the code displayed somewhat nicely.

1

There are 1 answers

2
Yash Joshi On BEST ANSWER

Thanks for this question, you can use prettier to format the code. You may need to configure different parser based on the language or framework you are using.

Here is a sample codesandbox for formatting JS code. Link: https://codesandbox.io/s/currying-architecture-tm785?file=/src/App.js

Code for the main file:

import React from "react";
import prettier from "prettier/standalone";
import babylon from "prettier/parser-babel";

import "./styles.css";

export default function App() {
  const [code, setCode] = React.useState(`
        const a = "abc";


                const b = 'a'


           console.log(a);       
  `);

  const formatCode = () => {
    const formattedCode = prettier.format(code, {
      parser: "babel",
      plugins: [babylon]
    });

    setCode(formattedCode);
  };

  return (
    <div className="App">
      <textarea
        style={{ height: "100px", width: "100%", display: "block" }}
        value={code}
      />
      <button onClick={formatCode}>Format Code with Prettier</button>
    </div>
  );
}

Hope this helps!