Thursday, August 4, 2022
HomeWeb DevelopmentThe information to syntax highlighting in React

The information to syntax highlighting in React


Introduction

Software program builders learn as a lot code as they write. Due to this fact, to boost code readability, you shouldn’t solely attempt to put in writing readable code, but in addition to use applicable code formatting and syntax highlighting.

There are a number of programming and non-programming pc languages builders use every day. Every language comes with its syntax and, subsequently, syntax highlighting wants. To use syntax highlighting within the browser surroundings, libraries similar to Prism, Spotlight, and React syntax highlighter exist.

Every of those libraries has its strengths and weaknesses. A few of these libraries have been developed to be used with plain JavaScript, whereas others additionally help front-end frameworks like React.

This text will probably be an entire information to in style syntax-highlighting libraries like Prism and the best way to use them with React. We may also spotlight their strengths and weaknesses.

Desk of Contents

Introduction to prism.js

Prism is without doubt one of the hottest syntax highlighting libraries in JavaScript, with over 10,000 stars on GitHub. You should utilize it with plain JavaScript and frameworks similar to React. It helps a number of languages and has a wealthy ecosystem of themes and plugins that you need to use to increase its core performance.

To get a style of Prism, you’ll be able to shortly load it through CDN or obtain the supply code and add it to your markup utilizing a script tag. You too can obtain help for particular languages, themes, and plugins.

The core Prism library has a small footprint. Its minified and gzipped bundle measurement is roughly 2kB. Although the extra themes and plugins you obtain with core Prism to increase its performance could enhance the bundle measurement, you’ve complete management over which plugins or themes you’ll be able to obtain.

Moreover, in contrast to some syntax highlighters, Prism forces you to make use of semantic HTML for code presentation. The customizability, and a number of other different options, make Prism a well-liked selection for syntax highlighting.

Babel-plugin-prismjs is a useful bundle for utilizing Prism with Babel and webpack. Within the subsequent part, we will take a look at utilizing this plugin in a React utility.

Learn how to use Prism for syntax highlighting in React

As talked about within the earlier part, the simplest and quickest approach to get began with Prism is to make use of a CDN. Although a CDN could also be handy, it’s nearly all the time not possible to make use of it when working with frameworks similar to React. Due to this fact, you will want to put in it from NPM.


Extra nice articles from LogRocket:


sh
# utilizing npm
npm set up prismjs
# utilizing yarn
yarn add prismjs

The babel-plugin-prismjs Babel plugin is useful if you wish to use Prism for syntax highlighting in a React utility. You should utilize it to configure the languages, themes, and plugins to bundle with Prism. You’ll be able to set up it as a improvement dependency from NPM.

sh
# utilizing npm
npm i -D babel-plugin-prismjs
# utilizing yarn
yarn add -D babel-plugin-prismjs

You should register the plugin in your Babel configuration file like so:

{
  "plugins": [
    ["prismjs", {
        "languages": ["javascript", "css", "markup"],
        "plugins": ["line-numbers"],
        "theme": "twilight",
        "css": true
    }]
  ]
}

You’ll be able to embody the languages, plugins, and themes your challenge wants within the configuration file. Verify the Prism documentation for a whole listing of the supported languages and the accessible themes and plugins you need to use.

Arrange a customized react utility if you wish to use the babel-plugin-prismjs plugin. Nonetheless, to make use of it with Create React App, you will want to eject — I imagine doing so defeats the aim of utilizing Create React App.

Moreover, a number of React syntax highlighting packages use Prism underneath the hood. We will discover a few of them within the sections under. You would possibly think about using one in all them in case your challenge shouldn’t be based mostly on a customized React utility.

After finishing the setup described above, import Prism into your React part and invoke the highlightAll methodology within the useEffect hook like so:

import React, { useEffect } from "react";
import Prism from "prismjs";

operate App() {
  useEffect(() => {
    Prism.highlightAll();
  });
  return (
    <div>
      <p>
        You'll be able to declare a variable in JavaScript utilizing the
        const, let or var key phrase. </p> </div> ); } export default App;

When utilizing Prism, it’s essential wrap inline code within the code HTML tag, and relying on the language you might be highlighting, apply the suitable class to it. The category identify ought to take the shape lang-xxxx or language-xxxx.

The xxxx is a placeholder for the language. Within the instance above, we added the lang-javascript class to the code components since we’re highlighting JavaScript code.

As identified within the earlier part, Prism forces you to make use of semantic HTML when including code to your markup. Due to this fact, you need to wrap your code in pre components when highlighting blocks of code.

It’s handy to extract your performance to a separate part for reusability when rendering code blocks, like within the instance under. You’ll be able to go the code block and the language as props.

import React, { useEffect } from "react";
import Prism from "prismjs";

const CodeBlock = ({ code, language }) => {
  useEffect(() => {
    Prism.highlightAll();
  }, []);
  return (
    <pre>
      <code youngsters={code} className={`language-${language}`} />
    </pre>
  );
};

export default CodeBlock;

Learn how to use prism-react-renderer

As an alternative of utilizing Prism with a React utility as we did within the earlier part, you can too use prism-react-renderer to spotlight code in your React utility.

prism-react-renderer comes bundled with a modified model of Prism, and it offers help for among the frequent languages and themes by default.

You should set up prismreactrenderer from NPM to make use of it.

sh
# set up with npm
npm i prism-react-renderer

# set up with yarn
yarn add prism-react-renderer

Prism react renderer exposes Spotlight as its major part and exports some default props, which you’ll go to Spotlight. You should go a render prop to the Spotlight part as within the instance under.

import React from "react";
import Spotlight, { defaultProps } from "prism-react-renderer";

export const CodeBlock = ({ code, language }) =&gt; {
  return (
    &lt;Spotlight {...defaultProps} code={code} language={language}&gt;
      {({ className, fashion, tokens, getLineProps, getTokenProps }) =&gt; {
        return (
          &lt;pre className={className} fashion={fashion}&gt;
            <code>
                  {tokens.map((line, idx) => {
                    return (
                      <div {...getLineProps({ line, key: `line-${idx}` })}>
                        {line.map((token, i) => {
                          return (
                            <span
                              {...getTokenProps({ token, key: `token-${i}` })}
                            />
                          );
                        })}
                      </div>
                    );
                  })}
                </code>
          &lt;/pre&gt;
        );
      }}
    &lt;/Spotlight&gt;
  );
};
</code></pre>

The above code block illustrates how one can spotlight a easy code block with the prism-react-renderer bundle. The Spotlight part passes a number of arguments to the render prop. You should utilize these props to render your code block like within the above instance.

You’ll be able to import the CodeBlock part we wrote above and go within the code and language props when rendering a code block. Doing so makes the part reusable.

import { CodeBlock } from "./CodeBlock";

const code = `
  const add = (a, b) => {
    return a + b;
  }
`;

operate MyComponent() {
  return (
    <div className="App">
      <CodeBlock code={code} language="javascript" />
    </div>
  );
}

Introduction to react-syntax-highlighter

react-syntax-highlighter is a React part for syntax highlighting in React. It makes use of Prism and Spotlight for syntax highlighting internally. Prism and Spotlight are among the many in style syntax highlighters for the browser surroundings.

You set up it from NPM and go within the needed props to begin utilizing react-syntax-highlighter.

sh
# utilizing npm
npm i react-syntax-highlighter

# utilizing yarn
yarn add react-syntax-highlighter

Not like among the packages described within the earlier sections, you don’t want further configuration to get this to work. Allow us to take a look at the best way to use it for syntax highlighting in React within the part under.

Learn how to use react-syntax-highlighter

After putting in react-syntax-highlighter, you’ll be able to import and render the mandatory part. As talked about within the earlier part, you’ll be able to select to both use Spotlight or Prism for highlighting.

Nonetheless, react-syntax-highlighter exports a part that makes use of spotlight by default. You should go the configuration possibility as props when rendering it like so:

import SyntaxHighlighter from "react-syntax-highlighter";
import { dracula } from "react-syntax-highlighter/dist/esm/types/hljs";

const code = `
console.log("hey world");
`;

operate App() {
  return (
      <SyntaxHighlighter youngsters={code} language="javascript" fashion={dracula} />
  );
}

As illustrated within the instance above, you go the code you wish to spotlight and the formatting language as string props. Along with the youngsters, language, and fashion props, there are a number of different formatting choices, similar to displaying and styling line numbers. Do verify the documentation for a whole listing of choices accessible.

As identified within the introduction, react-syntax-highlighter comes bundled with each Spotlight and Prism. As an alternative of utilizing Spotlight as within the above instance, you can too use Prism. When utilizing Prism, you additionally must import the Prism theme you wish to use, like within the instance under.

import { Prism as SyntaxHighlighter } from 'react-syntax-highlighter';
import { darkish } from 'react-syntax-highlighter/dist/esm/types/prism';

Although the tactic for utilizing it described above masses a number of options out of the field, it comes with a big footprint. Due to this fact, react-syntax-highlighter has a light-weight construct for loading and bundling solely the functionalities you want.

Nonetheless, bear in mind that the sunshine construct doesn’t include default styling. Due to this fact, it’s essential import the theme by your self. Moreover, import and register the languages utilizing the registerLanguage operate as within the instance under.

import { Gentle as SyntaxHighlighter } from "react-syntax-highlighter";

import typescript from "react-syntax-highlighter/dist/esm/languages/hljs/typescript";
import a11yDark from "react-syntax-highlighter/dist/esm/types/hljs/a11y-dark";

SyntaxHighlighter.registerLanguage('typescript', typescript);

The above instance for the sunshine construct makes use of Spotlight by default. You should utilize Prism equally. Import PrismLight as an alternative of Gentle, as within the instance under.

import { PrismLight as SyntaxHighlighter } from "react-syntax-highlighter";

import typescript from "react-syntax-highlighter/dist/esm/languages/prism/typescript";
import a11yDark from "react-syntax-highlighter/dist/esm/types/prism/a11y-dark";

SyntaxHighlighter.registerLanguage('typescript', typescript);

Verify the documentation for extra options and limitations of the react-syntax-highlighter bundle.

Introduction to Rainbow

The syntax highlighting libraries talked about above are the most well-liked and best to make use of with React.

Nonetheless, they aren’t the one syntax highlighting libraries. Rainbow is one other easy and light-weight bundle for syntax highlighting. It’s value exploring, particularly when you find yourself not utilizing a framework like React.

Conclusion

Syntax highlighting is inevitable when publishing content material containing inline code snippets or code blocks to extend readability. There are a number of libraries you’ll be able to choose from when highlighting code within the browser surroundings. Hottest among the many syntax highlighting libraries are Prism and Spotlight.

As talked about above, you need to use some syntax highlighting libraries with plain JavaScript and others with frameworks like React. The babel-plugin-prismjs Babel plugin helps you to use Prism with bundlers similar to webpack. Nonetheless, you can too use React packages similar to prism-react-renderer or react-syntax-highlighter that bundle modified variations of Prism.

Prism has a small footprint when contemplating the core library. Nonetheless, it turns into sizable if you lengthen its core functionalities with further themes and plugins.

Although our focus on this article was on syntax highlighters usable with React, a number of different Syntax highlighting libraries like Rainbow are additionally value exploring. Rainbow is a good syntax highlighting library to contemplate if you’re not utilizing a front-end framework like React.

Full visibility into manufacturing React apps

Debugging React functions could be troublesome, particularly when customers expertise points which can be arduous to breed. When you’re fascinated by monitoring and monitoring Redux state, robotically surfacing JavaScript errors, and monitoring sluggish community requests and part load time, strive LogRocket.

LogRocket is sort of a DVR for net and cell apps, recording actually all the things that occurs in your React app. As an alternative of guessing why issues occur, you’ll be able to combination and report on what state your utility was in when a difficulty occurred. LogRocket additionally displays your app’s efficiency, reporting with metrics like shopper CPU load, shopper reminiscence utilization, and extra.

The LogRocket Redux middleware bundle provides an additional layer of visibility into your consumer classes. LogRocket logs all actions and state out of your Redux shops.

Modernize the way you debug your React apps — .

RELATED ARTICLES

LEAVE A REPLY

Please enter your comment!
Please enter your name here

- Advertisment -
Google search engine

Most Popular

Recent Comments