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
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.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 aJSX.Element[] = [];
which is not a valid JSX element, you could just map overmyMap
and return it.You can use the
white-space: pre-wrap
CSS property on the text rendering component to render then
as new lines in this case.