What is the best way to create a line break within a loop in React?

I have a react component that I need to format into multiple lines, specifically having 2 boxes on top and 3 below in a looped return. The desired layout is to stack the boxes in 2x2 or 2x3 depending on the total number of boxes generated by the loop.

So, my question is, how can I add line breaks within a looped return in React?

Here is the code snippet:

import React from 'react'
import classnames from 'classnames'

export default class Tile extends React.Component {
 constructor( props ) {
  super( props )
}

componentWillAppear( done ) {
// Animation logic here
}

componentDidAppear() {
// Transition effect implementation
}

onClick = event => {
// Click event handling
}

render() {
// Render method for generating tiles

return (

  <li ref="container" className={ classes } onClick={ this.onClick }>
    <span className="Tile-content">{ this.props.text }</span>
  </li>

)
  }
}

Another requested code snippet:

render() {
// Rendering method for creating tiles dynamically

 let buttonClasses = classnames( 'Btn', 'Btn--isOrange', 'Btn--
 isContinue', {
  'u-transparent': !this.state.complete
})

   return (
  <div ref="main" className="js-main State">
    <p className="Question-Body">
      { this.props.slide.body }
    </p>
    <button ref="continue" className={ buttonClasses } onClick={ 
  this.onContinue }>{ this.props.slide.continue }</button>
  </div>
  )
  }

Answer №1

To add a line break, you must do it manually:

let tiles = this.props.slide.answers
  .map( ( answer, index ) => {
    let id = 'answer' + index
    let tile = <Tile
      key={ id }
      id={ id }
      value={ answer.value }
      text={ answer.text }
      selected={ this.selected.has( id ) }
      onClick={ this.onTileClick }
    />
    return index == 1 ? [tile, <br/>] : tile;
  })

This converts [tile, tile, tile, tile] to

[tile, [tile, <br/>], tile, tile]

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

What is preventing my Express.js from running properly?

My express.js application stops running after reaching this point: node app.js info - socket.io started I'm looking for guidance on why this error occurs and how to resolve it. It seems like the issue lies within my app.js file, which I've inc ...

What is the reason behind div elements shifting when hovering over a particular element?

Currently, I have floated all my div elements (icons) to the left and margin-lefted them to create space in between. I've displayed them inline as well. However, when I hover over one element (icon), the rest of the elements move. Can you please help ...

Infinite scroll layout meets Semantic UI visibility for a dynamic user experience

I am attempting to implement an infinite scrolling Masonry layout within the Semantic UI framework, utilizing the pre-existing visibility function. While everything appears to be functioning correctly, I am encountering difficulties with getting Masonry t ...

Transform JavaScript AJAX to HttpWebRequest implementation code

Is it possible to mimic an AJAX call to a web service within a console application using HttpWebRequest? Here is the source request: var webRequest = Sys.Net.WebServiceProxy.invoke('', 'MyMethod', false, {p1:aa,p2:bb,p3:123}, onSucc ...

What is the best way to handle an OR scenario in Playwright?

The Playwright documentation explains that a comma-separated list of CSS selectors will match all elements that can be selected by one of the selectors in that list. However, when I try to implement this, it doesn't seem to work as expected. For exam ...

The challenge of executing JavaScript in the correct order

I am facing an issue where 5 always prints before 4 in my code snippet below. I expected the callback to postUsers within a return statement from matchAgainstAD to wait for the completion of the for loop and ad lookup before returning. What is the simple ...

The pre-line white-space property is not functioning as anticipated in my CSS code

content: string; this.content = "There was an issue processing your request. Please try using the browser back button."; .content{ white-space: pre-line; } <div class="card-body text-center"> <span class="content"> {{ content }} </span& ...

What is the best approach to managing this scenario where the document is ready?

Just a quick question. I have several JavaScript functions written in this format: var app={ start:function(){ //do something and call calculate }, //end start calculate:function(){ //do more stuff } //end calculate }; //en ...

How to Dynamically Set AngularJS Filter (like date or currency) Using Variables

When working with Angular, it's possible to easily apply filters to format variables, like so: {{ myDate | date }} {{ myMoney | currency }} But, is there a way to dynamically set the filter type in a more flexible manner as shown below? // controll ...

Invoke a function within one component using another component

I am facing an issue with deleting playlists displayed on my page. These playlists are fetched from an external API and each playlist has a delete button which is supposed to remove the playlist both from the API and the view. The deletion process works s ...

Deleting a row from a Material UI table: Step-by-step guide

I'm currently working on a CRUD table using React and Material-UI. I have successfully fetched data from an API and displayed it in a table, but now I am facing a challenge with deleting a row. As this is my first project in React, I am seeking guidan ...

Reasons why a functional component may not trigger a rerender after a state change using useReducer()

When using react Hooks, specifically useReducer, I found that although the state changes, the functional component does not rerender. Additionally, when trying to open the drawer by pressing a button in the menu, even though the state changes the drawer re ...

What could be causing my Alert component to keep triggering repeatedly?

This is my custom React Native script. import React, { useState, useEffect } from 'react'; import { Alert, View, Image, StyleSheet, Animated, Easing, TouchableOpacity, Text, ScrollView, ImageBackground, Dimensions, TextInput } from 'react-na ...

How can I customize the appearance of a specific element within TextField from MUI using styled-components?

Using the MUI TextField component, I am passing a messageEdited useMemo function as the value property. index.jsx import React, { useMemo } from "react"; import Box from "@mui/material/Box"; import TextField from "@mui/material/T ...

Hazy placeholder in Material UI Select alongside the selected value

In the code snippet below, you can see my Select component. I've implemented a data fetching process and within the useEffect, I am setting the categoryId. However, an issue arises where the placeholder is displayed in the background as shown in this ...

Version 5.3 of Laravel combined with Vue 2

Working with Vue 2 in a fresh Laravel 5.3 project, I'm faced with a challenge regarding binding a URL in the Laravel format. I've extracted some configuration rows from a database and my goal is to iterate over them to display the data, followed ...

Template string use in Styled Components causing issues with hover functionality

I have a styled component where I am trying to change the background color when its parent is hovered over. Currently, the hover effect is not working and I'm unsure why. const Wrapper = styled('div')` position: relative; margin-bott ...

Which HTML tags can be activated with JavaScript to be interactive?

I'm currently diving into the world of JavaScript and one of the initial code snippets I've encountered is onclick. So far, I've seen it utilized in form buttons like this: <input type="button" onclick="checkName()" value="Check name" / ...

A step-by-step guide to moving Vue .prototype to its own file

I have a couple of functions that I need to add to Vue's .prototype. However, I don't want to clutter up the main.js file. I attempted to move the prototypes like this: //main.js import "./vue-extensions/prototypes"; ...

What is the functionality of the "async:false" setting in a jQuery AJAX request?

I understand the purpose and usage of {async:false} in jQuery AJAX requests. However, I am curious to know how this operates synchronously. What is the mechanism behind it? ...