Ad

Render Code To Page Using JSX Whilst Preserving Line Breaks

- 1 answer

I am trying to use a field that will contain a load of code that contains line breaks and tabs. I want it to render and retain the tabs and line breaks.

Basically I want it to look like the code is formatted in stack overflow when I output it. When I use string literals it doesn't retain the tabs and line breaks.

Below is my code

import React, { useContext } from 'react'
import FunctionalContext from '../../context/functional/functionalContext';


const FunctionalComponent = () => {
  const functionalContext = useContext(FunctionalContext);

  return (
    <div>
      <h1>Classes</h1>
      <h2>Classes</h2>
      <code>{`
          import React from 'react'
        constructor() {
          super()
      `}
      </code>



    </div>
  )
}

export default FunctionalComponent

Ad

Answer

The code element isn't preformatted by default. You can either apply one of the white-space styles to it, or put it in a pre element.

I think you'll struggle with getting the tabs rendered in a useful way, though. You may want to expand them out to whatever tab stops were being used by the author before outputting instead.

Example of using <pre><code>...</code></pre>:

const Example = () => {
  const code =
`
import React from 'react';

class Foo extends React.Component {
    constructor() {
        super();
    }
}`;

  return (
    <div>
      <h1>Classes</h1>
      <h2>Classes</h2>
      <pre><code>{code}</code></pre>
    </div>
  );
}

ReactDOM.render(<Example/>, document.getElementById("root"));
<div id="root"></div>

<script src="https://cdnjs.cloudflare.com/ajax/libs/react/16.10.2/umd/react.production.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react-dom/16.10.2/umd/react-dom.production.min.js"></script>

Example of using white-space styling instead:

const Example = () => {
  const code =
`
import React from 'react';

class Foo extends React.Component {
    constructor() {
        super();
    }
}`;

  return (
    <div>
      <h1>Classes</h1>
      <h2>Classes</h2>
      <code className="block">{code}</code>
    </div>
  );
}

ReactDOM.render(<Example/>, document.getElementById("root"));
.block {
    display: block;
    white-space: pre;
}
<div id="root"></div>

<script src="https://cdnjs.cloudflare.com/ajax/libs/react/16.10.2/umd/react.production.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react-dom/16.10.2/umd/react-dom.production.min.js"></script>

I also included display: block because by default code is inline.

Ad
source: stackoverflow.com
Ad