Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Formatting code with <pre> tag in React and JSX

I am trying to use the pre tag inside of JSX.When you use the pre tag in JSX, it doesn't format at all. Why? In order to use the pre tag I need to do something like this:

const someCodeIWantToFormat = "var foo = 1" const preBlock = { __html: "<pre>" + pythonCode + "</pre>" }; return(   <div dangerouslySetInnerHTML={ preBlock } />; ) 

Why?

like image 252
user2465134 Avatar asked Jun 16 '16 00:06

user2465134


People also ask

Can we use script tag in JSX?

To add script tag or code in head tag <head> , use react-helmet package.

What is JSX element []?

What is JSX? JSX stands for JavaScript XML. JSX allows us to write HTML in React. JSX makes it easier to write and add HTML in React.

Can I use style in JSX?

Note: In JSX, JavaScript expressions are written inside curly braces, and since JavaScript objects also use curly braces, the styling in the example above is written inside two sets of curly braces {{}} .

What is JSX format?

JSX stands for JavaScript XML. It is simply a syntax extension of JavaScript. It allows us to directly write HTML in React (within JavaScript code). It is easy to create a template using JSX in React, but it is not a simple template language instead it comes with the full power of JavaScript.


1 Answers

Use template literals

Template literals allow the use of multi-line strings which preserve leading/trailing white-space and new lines.

class SomeComponent extends React.Component {    render() {         return (           <pre>{`             Hello   ,                World   .           `}</pre>         )     } } 

class SomeComponent extends React.Component {     render() {          return (            <pre>{`              Hello   ,                 World   .            `}</pre>          )      }  }    ReactDOM.render(    <SomeComponent />,     document.getElementById('pre')  )
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/0.14.3/react.min.js"></script>  <script src="https://cdnjs.cloudflare.com/ajax/libs/react/0.14.3/react-dom.min.js"></script>    <!-- The content rendered into this tag should match the content below. -->  <div id="pre"></div>    <pre>              Hello   ,              World   .  </pre>
like image 86
gfullam Avatar answered Oct 13 '22 10:10

gfullam