简体   繁体   中英

React.js New Line and Returns

I'm calling an API that responds with items (objects) that have the general form:

{
    "comment":"Here is a comment that has a new line \n, a return \r and a tab in it for this item: \r\tSome Item"
}

This gets added to the react app:

<Item>{item.comment}</Item>

The problem is the new line, tab and returns aren't included. Does anyone know a syntax where this will be respected without a monster search and replace (this API returns thousands of these records, I'd prefer not to have to iterate over each one to insert "<br />" etc).

Unfortunately, I don't think ReactJS supports this out of the box. I found something that you can use here - Newline in react string

This solved my problem:

import React from 'react';


//styles
import './index.css';

/**
 * Used to preserve whitespace for text values. For instance, \n, \r, and \t characters
 * @param {Object} props
 * @param {string} props.text The text you want to preserve whitespace from. 
 */
function PreserveWhitespace({text}) {

    return (
        <span className="preserve-whitespace">
             {text}
        </span>
    );

}

export default PreserveWhitespace;

And the CSS:

.preserve-whitespace {
  white-space: pre-wrap;
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM