Struggling to add a line break in my code

class Test extends React.Component{
state={name: "John", numTimes: 2};

render() {
  let output = ""

  for (let i = 1; i <= this.state.numTimes; i++) {
    let evenOdd = i % 2

    if (evenOdd === 0) {
      output += i + ". Hello " + this.state.name + "!"
    } else {
      output += i + ". Hello " + this.state.name
    }
  }

  return <p>{output}</p>
}

}
ReactDOM.render(<Test /> , document.getElementById("react"));
<div id="react"></div>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react-dom.min.js"></script>

I am in the process of designing an application where users can input their name and specify how many times they want it to be displayed.

In my attempts to customize the output, I have experimented with styles and adding line breaks using "\n" and breaklines.

render() {
  let output = ""

  for (let i = 1; i <= this.state.numTimes; i++) {
    let evenOdd = i % 2

    if (evenOdd === 0) {
      output += i + ". Hello " + this.state.name + "!"
    } else {
      output += i + ". Hello " + this.state.name
    }
  }

  return <p>{output}</p>
}

Within my loop, odd numbers will not display an exclamation mark but even numbers will, resulting in a sequence like:


1. Hello John
2. Hello John!

and so forth...

Despite no occurrence errors, the current output appears as:

  1. Hello John 2. Hello John!

Answer №1

Consider utilizing the div element since it is a block level element, allowing it to automatically move to the next line.

let output= []
  for (let i = 1; i <= this.state.numTimes; i++) {
    let evenOdd = i % 2
    if (evenOdd === 0) {
      output.push(<div key={i}>{i + ". Hello " + this.state.name + "!"}</div>) 
    } else {
      output.push( <div key={i}>{i + ". Hello " + this.state.name}</div>)
    }
  }

Answer №2

Have you experimented with this?

result += i + ". Greetings " + this.state.name + "!"+ {"\n"}

Answer №3

Give this a try:

 let result = ""
      for (let count = 1; count <= this.state.numTimes; count++) {
        let evenOrOdd = count % 2
        if (evenOrOdd === 0) {
          result += count + ". Hey there, " + this.state.name + "!"+'\n'
        } else {
          result += count + ". Hey there, " + this.state.name
        }
      }
return <p>{{result}}</p>

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

Tips for accessing payment details from a stripe paymentElement component in a React application

Here is a basic code snippet for setting up recurring payments in Stripe: await stripe ?.confirmSetup({ elements, confirmParams: { return_url: url, }, }) After browsing through the documentation and the internet, I have two unanswere ...

Tips for defining a function without an arrow as a parameter

Understand that there may be individuals quick to flag this as a duplicate question, but trust me when I say that I have exhaustively searched on Google for almost an hour before turning to ask here. methods: { stylizeHeader: debounce(event => { ...

Searching for a streamlined approach to retrieve a segment of a string

I'm currently working with JavaScript and TypeScript. Within my code, I encountered a scenario where I have a string that might contain certain tags indicating importance or urgency. Here are a couple of examples: A: "Remind me to go to the store to ...

What is the best way to retrieve an object value within an if statement?

What can I do to ensure that the line within the if statement functions properly? const player1 = { name: "Ashley", color: "purple", isTurn: true, play: function() { if (this.isTrue) { return `this["name"] is current ...

Having difficulty in setting a Cookie with php

Working on integrating social login, I attempted logging in with Facebook. Upon successful authentication of the user, I aim to retrieve their value and store their ID in a cookie to establish a session throughout the site. Below is the code snippet, < ...

Unable to locate property 'location' due to being undefined

When trying to use the react-router-dom 4.0.0 library, an error was encountered: Uncaught TypeError: Cannot read property 'location' of undefined The issue seems to be with browserHistory. Previously, I had been using react-router 2.x.x witho ...

The popover displays the text "[object Object]" when triggered by an ajax event

Upon observing the image, I noticed that my bootstrap popover is triggering and displaying “[object Object]” instead of the database data I retrieved. After adding logs to the JavaScript AJAX code, I can see that the data is being retrieved, but it i ...

What could be causing the error when attempting to release this Node-MySQL pool?

My first attempt at utilizing connection pooling is with Node.js. I crafted a database connection module in Node.js to establish a single connection, which is then referenced within a pooling function for later use when passed to different modules. /* D ...

Activate Bootstrap tooltip when input element is focused, and then when the next input element is selected

I'm trying to activate a tooltip on an input element within a table. My goal is to trigger the tooltip when either that specific input element or the adjacent input element in the table are focused. Below is the HTML structure: <td class="fea ...

The functionality of the Bootstrap4 accordion is not functioning according to my expectations

My goal is to create a unique e-commerce checkout page design. Each panel would be opened sequentially, with the next panel unfreezing when the action button of the current panel is clicked. However, I seem to be making a mistake as it is not working as in ...

Incorporating a PHP file containing both PHP and JavaScript variables into an AJAX document

I'm facing an issue with my application that involves a language file called "lang.php", along with "index.php" and "ajax.php" files. The "lang.php" file contains both PHP and JavaScript variables which I include in both "index.php" and "ajax.php" to ...

Building a layout grid using the box component and sx property

With Material UI v5, it is said that you can create almost anything using the sx prop. However, I am struggling to create a simple grid using the grid feature. You can see what my desired grid looks like here. I have made unsuccessful attempts at using th ...

Axios sending a 400 Bad Request to Django due to a missing required field

I'm having issues sending a POST request from my React frontend using Axios. import axios from 'axios' axios.post('http://server:port/auth/login', { username: 'admin', password: 'MY_PASSWORD', }, { ...

What steps do I need to take to get a website up and running with the index.html

After successfully hosting my website, I encountered an issue where it opens the index of the website (a list of files added via FTP) instead of the Index.html page. Can you advise on how to resolve this? Your assistance is greatly appreciated. ...

Altering the input field's content in response to a button click through JavaScript's addEventListener function

I am struggling to get the input text from a form field to change when a button is clicked using JavaScript. I can't seem to figure out why it isn't working correctly. Any assistance would be greatly appreciated. <!doctype html> & ...

Tips for stopping the loading of background images on an image slider

I am utilizing unslider to showcase an image slider on the landing page of my website. The slides are designed with background images in the CSS, and they adjust based on the media query. My concern is that I don't want all the slider images to load a ...

Is it possible to utilize npm request multiple times within a single route and showcase the outcomes on a single page?

Is it possible to utilize the node module "request" multiple times within a single route, and have the outcomes presented on a solitary rendered ejs template page? Objective: The aim is to exhibit eBook details from the iTunes Store by utilizing their Sea ...

Adjust the clarity of the elements within my HTML document

I have been working on creating a login page that will appear in front of the main webpage. Through my online research, I discovered a technique to blur the main webpage background until the user logs in. Below is the code snippet: HTML: <div id="logi ...

Swapping out the default JavaScript random number generator for my custom JSON-based solution

I've been working on creating a D3 graph to display my data. After following a tutorial, I arrived at this particular piece of code: // 8. An array of objects of length N. Each object has key -> value pair, the key being "y" and the value is a r ...

An empty constant object can trigger an endless cycle of re-rendering

Consider this simplified scenario: export function myCustomHook<TData = Record<string,string>> (data?: TData) { const [output, setOutput] = useState<number>(); const customFunction(data?: TData) { //In a real scenario : p ...