Ways to display JSX with formatted new lines and spaces in React.js?

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.

Answer №1

To maintain line breaks, you should utilize the pre element. This will ensure that new lines are kept intact in your code snippet:

      <section>
        <h6>Question:</h6>
        <pre>{question[0]}</pre>
        <br />
        <h6>Answer:</h6>
        <pre>{question[1]}</pre>
      </section>

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Resetting the positions of images can be done by following these

I'm currently in the process of developing a game and need assistance with implementing a game end function. Can you provide guidance on how to reset all images back to their original positions? ...

What is the best way to retrieve the following database results after clicking a button with Node.js?

Currently, my Node.js setup is successfully connected to my webpage and pulling data from a MySQL database. I have managed to display the first row of data as button values in the HTML code below. However, what I now want is for the user to be able to cl ...

extracting values from deeply nested JSON array in JavaScript

Is there a way to extract values from a deeply nested JSON array? I'm looking to retrieve all pairs of (nameValue and value) from the JSON provided below var json = [{ name: 'Firstgroup', elements: [{ ...

Attributes required are not functional on mobile devices

Good day! I have encountered an issue with the required attribute on a form on my website. It seems to be working perfectly on my browser, but not on mobile devices. Has anyone else experienced difficulties with jQuery, JavaScript, or Node packages? <f ...

Tips for specifically targeting the clicked table row using angularJS directives ng-show and ng-hide

Seeking assistance with implementing a toggle function in an angularJS app for showing/hiding a specific table data section. Currently, the toggling functionality is working, but it toggles every row in the table instead of just the clicked row. See this e ...

Having trouble implementing uppercase text in Bootstrap editable modules

Recently, I implemented the bootstrap editable function in my application and it was functioning perfectly. However, I am now looking to have the editable text always display in uppercase format. Unfortunately, I am unsure of how to achieve this. Any sugge ...

Transforming JSON data into a visually appealing pie chart using highcharts

I'm having trouble loading my JSON string output into a highcharts pie chart category. The chart is not displaying properly. Here is the JSON string I am working with: var json = {"{\"name\":\"BillToMobile\"}":{"y":2.35},"{\ ...

Use PHP to dynamically assign a class to each <option> element within a loop

How do I go about adding a CSS class to every option within my code? Here is the PHP code provided, and you can refer to the screenshot below for where the class property should be placed - what adjustments should be made in order to include a class in eac ...

Straining data in text input fields using bootstrap

Looking for a way to filter data with bootstrap/jquery without using tables, just div rows and columns. Check out an example of how my form looks Here's a snippet of my code: <div class="row"> <div class="col-md-4"> <input class= ...

Using either jQueryUI or BlockUI modal, you can create a dialog that covers only a specific

Is there a way to have a modal dialog specifically over a certain div container on a webpage? I've been searching for answers but haven't found anything regarding this with jQueryUI or BlockUI. Would modifying an existing overlay solution be the ...

Customizing the toString Method in a TypeScript Class for JavaScript Objects

I've been struggling with a particular issue for the past few days and I just can't seem to find a solution anywhere. Context: I currently have a TypeScript class that is defined like this: export class Client extends Person { claimNumber: s ...

I am seeking a way for my menu to dynamically change depending on the specific view in React, without using reactdom.render

After noticing that my app only shows the menu bar when I have dev tools open, I realized I might be doing something wrong. On my landing page, there is a menu bar with the app's logo, menu items, and a log-in button in my web app. Here's an exa ...

Display jQuery created hyperlinks in a modal window

I have taken on the task of revamping my school's outdated website. Please excuse the messy CSS and HTML as I am currently in the process of cleaning it up. Additionally, I am not well-versed in Javascript, so... Now, onto the issue at hand. The web ...

Overcoming validation hurdles with PHP and JavaScript

Our form pages have a majority of required fields, which are verified using JavaScript before being sent to a backend PHP app. Here is the form tag we utilize: <form name="order" method="post" action="http://company.com/config/_process.php?" id="order ...

Overlap between Material UI OutlinedInput and InputLabel components present an issue

What is the solution to the overlap problem between InputLabel and OutlinedInput in Material UI? Visit codesandbox for demo <FormControl> <InputLabel htmlFor="my-input">Email address</InputLabel> <OutlinedInput id=&q ...

JavaScriptCore now includes the loading of AMD modules

I am trying to incorporate a JavaScript module into JavascriptCore on iOS. To achieve this, I am fetching the file's text through a standard HTTP request on the iOS platform. Once I have obtained the entire string, I plan to parse it into the JSconte ...

Preventing special characters in an input field using Angular

I am trying to ensure that an input field is not left blank and does not include any special characters. My current validation method looks like this: if (value === '' || !value.trim()) { this.invalidNameFeedback = 'This field cannot ...

Transferring an object from Javascript to C++/CX following a C++/CX interface in Windows Runtime Components

As a newcomer to Windows Runtime Component, I've been exploring ways to accomplish the following task. I'm looking to extend a C++ interface in JavaScript. namespace MySDK { public interface class LoggerPlugin { public: virt ...

Exploring the power of SailsJS and sails.io integration in conjunction with Angular

Is there a way to initialize sails.io within an Angular2 service provider's zone in order to trigger change detection with websocket events? Another question: how can RXJS be used to subscribe to data streams from sails.io? I'm currently using ...

What causes certain CSS properties to scroll while others remain fixed?

I am experiencing a strange issue with my table. I am utilizing the tableHeadFixer jQuery plugin to create a fixed header with a scrollable table body. In my CSS, I have a class called table which is defined as follows: .table thead { color: blue; ...