0

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.

halfer
  • 19,824
  • 17
  • 99
  • 186
Hani Honey
  • 2,101
  • 11
  • 48
  • 76
  • 2
    You can use `prettier` to prettify your code. here is the link: https://prettier.io/docs/en/browser.html – Yash Joshi Apr 08 '20 at 05:53
  • @YashJoshi oh - I can use Prettier in the browser? I had no idea. And I can import it into my React component, yes? The trouble I had with other prettifiers is that they only supported node or vanilla JS. – Hani Honey Apr 08 '20 at 06:08
  • 1
    yes, the link that I sent is the guide to use prettier in the browser. Yeah you can import and use it. – Yash Joshi Apr 08 '20 at 07:00

1 Answers1

9

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!

Yash Joshi
  • 2,586
  • 1
  • 9
  • 18