Categories
React Answers

How to Format Code with the pre Tag in React and JSX?

Spread the love

Sometimes, we want to format code with the pre tag in React and JSX.

In this article, we’ll look at how to format code with the pre tag in React and JSX.

Format Code with the pre Tag in React and JSX

To format code with the pre tag in React and JSX, we should put the code we want to display in template literals.

For instance, we can write:

import React from "react";

export default function App() {
  const foo = 1;
  const bar = '"a b   c"';

  return (
    <pre>{`
    var foo = ${foo};
    var bar = ${bar};
  `}</pre>
  );
}

We interpolate the foo and bar strings in the code template string.

All the spaces in the template string are preserved.

Conclusion

To format code with the pre tag in React and JSX, we should put the code we want to display in template literals.

By John Au-Yeung

Web developer specializing in React, Vue, and front end development.

Leave a Reply

Your email address will not be published. Required fields are marked *