skip to Main Content

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

"nnAs an AI language model, I can write the code for the bubble sort algorithm in Python:nn```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]nn```nnTo use the above function for sorting, pass an unsorted list, as an argument:nn```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```nnThis is how the bubble sort works:nn- 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;
    };

2

Answers


  1. 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 textn 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>
          ))}
        </>
      );
    };
    
    Login or Signup to reply.
  2. You can use the white-space: pre-wrap CSS property on the text rendering component to render the n as new lines in this case.

    let lineBreakString = "nnAs an AI language model, I can write the code for the bubble sort algorithm in Python:nn```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]nn```nnTo use the above function for sorting, pass an unsorted list, as an argument:nn```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```nnThis is how the bubble sort works:nn- 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.";
    
    let textDiv = document.querySelector('#text-div');
    textDiv.innerHTML = lineBreakString;
    #text-div {
      white-space: pre-wrap;
    }
    <div id="text-div"></div>
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search