one-hand-octopus
one-hand-octopus

Reputation: 2763

How to automatically do line break in <pre> tag?

I'm trying to put a code snippet in my React application, what strange is no matter what I do, there is no line break in the snippet. Here is my code:

import React from 'react';
import './Hello.scss';

const Hello = () => {
    return (
        <>
            <div>
                Hello world!
            </div>
            <pre>
                npx create-react-app my-app
                cd my-app
                npm start
            </pre>
        </>
    )
}

export default Hello;

pre {
    font-size: 16px;
    overflow: auto;
    padding: 10px;
    background-color: #f8f8f8;
    border: 1px solid #ddd;
    white-space: pre-wrap; /* css-3 */
    white-space: -moz-pre-wrap; /* Mozilla, since 1999 */
    white-space: -pre-wrap; /* Opera 4-6 */
    white-space: -o-pre-wrap; /* Opera 7 */
    word-wrap: break-word; /* Internet Explorer 5.5+ */
}

I was expecting what's in the pre tag to be

npx create-react-app my-app
cd my-app
npm start

Instead I get:

npx create-react-app my-app cd my-app npm start

Any idea how I can make the pre work?

Upvotes: 4

Views: 2627

Answers (2)

web-sudo
web-sudo

Reputation: 686

<pre> tag works well with <br> tag when it comes to line break. Meaning you can insert <br /> tag and to do this you would need to replace the \n symbols by <br /> tags.

so the html code should be like this :

<pre>
    npx create-react-app my-app<br />
    cd my-app<br />
    npm start<br />
</pre>

Upvotes: 2

Yury Tarabanko
Yury Tarabanko

Reputation: 45106

You need to explicitly provide line breaks either by using string as children or by forcing {'\n'} at the line ends.

const Hello = () => {
    return (
        <React.Fragment>
            <div>
                Hello world!
            </div>
            <pre children={`npx create-react-app my-app
cd my-app
npm start
`} />
<pre>
npx create-react-app my-app{'\n'}
cd my-app{'\n'}
npm start{'\n'}
</pre>
        </React.Fragment>
    )
}

ReactDOM.render(<Hello />, document.getElementById('hello'))
pre {
  font-size: 16px;
  overflow: auto;
  padding: 10px;
  background-color: #f8f8f8;
  border: 1px solid #ddd;
  white-space: pre-wrap;
  /* css-3 */
  white-space: -moz-pre-wrap;
  /* Mozilla, since 1999 */
  white-space: -pre-wrap;
  /* Opera 4-6 */
  white-space: -o-pre-wrap;
  /* Opera 7 */
  word-wrap: break-word;
  /* Internet Explorer 5.5+ */
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/16.6.3/umd/react.production.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react-dom/16.6.3/umd/react-dom.production.min.js"></script>
<div id="hello"></div>

Upvotes: 4

Related Questions