Here is an image displaying a comparison between my console log and React website in Google Chrome.
Check out the Console log and Chrome website
Notice how the console output is neatly formatted with new lines and indents, while the text below "Generated Outputs" on the website lacks any formatting, causing all the text to be clustered together. The string, represented as a Javascript literal, appears like this -
'\n\n\npublic class FibonacciSequence {\n \n // recursive method\n public static int fibonacciRecursion(int n) {\n if (n == 0) return 0;\n else if (n == 1) return 1;\n else return fibonacciRecursion(n-1) + fibonacciRecursion(n-2);\n }\n \n // iterative method\n public static int fibonacciIterative(int n) {\n int a = 0, b = 1, c;\n if (n == 0) return a;\n for (int i = 2; i <= n; i++)\n {\n c = a + b;\n a = b;\n b = c;\n }\n return b;\n }\n \n public static void main (String[] args) {\n int n = 10;\n System.out.println("The Fibonacci number at position " + n + " is:");\n System.out.println("Using recursion: " + fibonacciRecursion(n));\n System.out.println("Using iteration: " + fibonacciIterative(n));\n }\n \n}'
The webpage fails to render the new lines and spaces. Is there a method to display the text with proper formatting similar to the console?
Note that the text is dynamically generated and not hardcoded, making it difficult to manually add spaces and new lines.
Currently, I am returning the following within the component -
<div>
<h5>Prompt:</h5>
{answer[0]}
<br />
<h5>Generated Output:</h5>
{answer[1]}
</div>
Where answer[1] holds the generated output variable.
Thank you.
I tried searching for solutions online, and one suggestion was to create a JavaScript function that replaces "\n" with "
" tag, then render the modified string using DangerouslySetInnerHTML. However, I would prefer avoiding DangerouslySetInnerHTML if possible.