Home > Back-end >  How to render JSX with new lines and spaces (React.js)?
How to render JSX with new lines and spaces (React.js)?

Time:11-30

Below is an image showing a side by side comparison of my console log and React website in Google Chrome.

Console log and Chrome website

Note that the console output is formatted nicely with new lines and indents. On the other hand, the text below "Generated Outputs" on the website has no formatting. All the text is clumped together. The string, as a Javascript literal, is 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 new lines and spaces are not rendered on the webpage. Is there any way I can render the new lines and spaces on the webpage so the text is formatted like in the console?

Note that the text is not hardcoded and auto-generated, so I can't hardcode the spaces and new lines.

Right now, I am returning the following in the component -

      <div>
        <h5>Prompt:</h5>
        {answer[0]}
        <br />
        <h5>Generated Output:</h5>
        {answer[1]}
      </div>

answer[1] is the variable that contains the generated output.

Thank you.

I looked for solutions online. One solution suggested to write a JavaScript function that replaces "\n" with a "br />" tag, and then render the new string with DangerouslySetInnerHTML. However, I would prefer a solution without having to use DangerouslySetInnerHTML if at all possible.

CodePudding user response:

You can use the pre element. It will preserve new lines like the following

      <div>
        <h5>Prompt:</h5>
        <pre>{answer[0]}</pre>
        <br />
        <h5>Generated Output:</h5>
        <pre>{answer[1]}</pre>
      </div>
  • Related