Search code examples
htmlreactjsspecial-characters

is it possible to render a string with \n with well formatted


When I using react to write a web page, I have a string like this:

"\n\nAs an AI language model, I can write the code for the bubble sort algorithm in Python:\n\n```\ndef bubble_sort(arr):\n n = len(arr)\n for i in range(n):\n for j in range(0, n-i-1):\n if arr[j] > arr[j+1] :\n arr[j], arr[j+1] = arr[j+1], arr[j]\n\n```\n\nTo use the above function for sorting, pass an unsorted list, as an argument:\n\n```\nmy_list = [5, 2, 9, 1, 5, 6, 3]\nbubble_sort(my_list)\nprint(my_list) # Output will be: [1, 2, 3, 5, 5, 6, 9]\n```\n\nThis is how the bubble sort works:\n\n- It compares the adjacent elements in an array and swaps them if the first element is greater than the second element.\n- The entire array is traversed one pass at a time.\n- After each pass, the largest element gets sorted to the end of the array, and the next pass ignores the last element since it is already sorted.\n- This process continues until the entire array is sorted."

is it possible to render it with a well formatted UI page? I have tried dangous html to render, seems just works with html, not with the format in my case. I have tried like this:

const renderChat = () => {
        const tagList: JSX.Element[] = [];
        myMap.forEach((value, key) => {
            tagList.push(
                <div key={uuid()} className="chat-message">
                    <div key={uuid()} className="message-time">{key}</div>
                    <div key={uuid()} className="message-text">
                        <pre>{value}</pre>
                    </div>
                </div>);
        });
        return tagList;
    };

Solution

  • In order to format the text, just wrap the text that you have within a <pre> element and add curly braces. The curly braces will allow you to treat the text as a JavaScript string, so we can use the escape sequences ('\n', '\r', '\v', etc) defined.

    <pre style={{ "text-align": "left" }}>
      {"your text\n another line"}
    </pre>
    

    React will escape any values in JSX, so even if you have dangerous html within the string, it is just going to be displayed as text. For example, <img src=xss onerror=\"alert('you have been hacked') would just be shown as text.

    The renderChat function component has to have the first letter capitalized. Capitalized types indicate that the JSX tag is referring to a React component (docs). And instead of returning a JSX.Element[] = []; which is not a valid JSX element, you could just map over myMap and return it.

    const RenderChat = () => {
      return (
        <>
          {myMap.map((value, key) => (
            <div key={uuid()} className="chat-message">
              <div key={uuid()} className="message-time">
                {key}
              </div>
              <div key={uuid()} className="message-text">
                <pre>{value}</pre>
              </div>
            </div>
          ))}
        </>
      );
    };