Niall Niall - 27 days ago 5
React JSX Question

Is there a better way of outputting multiple lines of example code when using jsx?

I am trying to output a block of example code as it is. Not HTML code i want to output javascript. I don't want the code rendered. I just want to show an example of how to do something. So for example I want this to be on my page:

if(a==b){
console.log('a is the same as b)
}


I have been researching online and the only option I can find is to surround it with {``}. However, this creates a problem that I have to include spaces and breaks manually like this:

{`if(a==b){`}
<br />
{`\u00A0\u00A0\u00A0\u00A0console.log('a is the same as b)`}
<br />
{`}`}


As you can see for a large block of example code this can get very cumbersome. Does anyone know a better way of outputting a larger block of example code using jsx?

Answer

const App = () => (
  <pre>{`
          if(a==b){ 
            console.log('a is the same as b)
          }
      `}
    </pre>
);

ReactDOM.render(<App />, document.getElementById('app'));
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react-dom.min.js"></script>
<div id="app"></div>

You can use the PRE tag.

The HTML pre element (or HTML Preformatted Text) represents preformatted text. Text within this element is typically displayed in a non-proportional ("monospace") font exactly as it is laid out in the file. Whitespace inside this element is displayed as typed.

Read more at https://developer.mozilla.org/en/docs/Web/HTML/Element/pre

    <pre>{`
          if(a==b){ 
            console.log('a is the same as b)
          }
      `}
    </pre>

enter image description here