Whenever the value of the div is evenly divisible by 5, set it to automatically move to the next column

I have created an array mapping that renders the expected output. However, I am facing a challenge where I want the items to go to the next column if their number is divisible by five while keeping the vertical alignment of divs. How can I achieve this without altering the vertical layout?

Below is the code I wrote which displays the list of items vertically without moving to the other side:

renderLogic() {
    let items = [0,1,2,3,4,5,6,7,8,9,10,11,12,13,14];
    return items.map((item) => {
        if(item % 5 === 0) {
            return (
                <div key = {item} style={{float: 'left'}}>
                    {item}
                </div>
            );
        } else {
            return (
                <div key = {item}>
                    {item}
                </div>
            );
        }
    });
 }

render() {
  return  (
    <div className="sample-container">
      {this.renderLogic()}
    </div>
  );
}

The current output of this code is as follows:

1
2
3
4
5
6
7
8
9
10
11 
12
13
14

However, my desired output is:

1  6  11
2  7  12
3  8  13
4  9  14
5  10

Answer №1

The reason behind this behavior is that div elements have a default style of display:block, causing them to take up the entire line. To resolve this issue, you can simply change their display property to display:inline-block.

However, there is an even simpler solution to your problem. You don't need to rely on JavaScript or use float. Just utilize Flexbox, a CSS rule, and you're good to go:

.container {
  display : flex;
  flex-direction: column;
  flex-wrap: wrap;
  border: green dashed 2px;
  height: 120px;
}

span {
  height : 20%;
  background: lightgreen;
  outline: blue solid 1px;
  
}
<div class="container">
  <span>1</span>
  <span>2</span>
  <span>3</span>
  <span>4</span>
  <span>5</span>
  <span>6</span>
  <span>7</span>
  <span>8</span>
  <span>9</span>
  <span>10</span>
  <span>11</span>
  <span>12</span>
  <span>13</span>
  <span>14</span>
</div>

For further information on Flexbox, check out this comprehensive guide to Flexbox

Answer №2

I approached this problem from a different angle. Instead of creating the div elements vertically, I decided to generate them horizontally one by one with their content, transitioning to a new row when necessary. This approach allows for flexibility in the number of rows needed.

One of the tricks I utilized was the CSS property clear (specifically set as clear: both). By using the clear property, it specifies which sides floating elements cannot float beside, acting as a "reset". The reset happens when j = 0, indicating the generation of the first element on that line. The formula i + divider * j + 1 effectively determines the index of the current element (you can verify this with some calculations).

class TodoApp extends React.Component {
  constructor(props) {
    super(props);
  }
  
    renderLogic() {
      let items = [0,1,2,3,4,5,6,7,8,9,10,11,12,13];
      let divider = 5;
      let boxes = [];
      
      for (let i = 0; i < divider; ++i) { 
          for (let j = 0; j < items.length / divider + 1; ++j) {
          
              if (i + divider * j >= items.length)
                  continue;
                  
              if (j == 0) {
                   boxes.push((
                    <div key = {i + divider * j + 1} class="box newline">
                        {i + divider * j + 1}
                    </div>
                ))
              } else {
                 boxes.push((
                    <div key = {i + divider * j + 1} class="box">
                        {i + divider * j + 1}
                    </div>
                ))
              }
             
          }
      }
      
      return boxes;
   }

  render() {
    return  (
      <div class="sample-container">
        {this.renderLogic()}
      </div>
    );
  }
}

ReactDOM.render(<TodoApp />, document.querySelector("#app"))
.sample-container {
  background-color: green;
}

.box {
  background-color: green;
  border: 1px solid black;
  float: left;
  margin: 5px;
  width: 50px;
  height: 50px;
}

.newline {
  clear: both;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/16.6.3/umd/react.production.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react-dom/16.6.3/umd/react-dom.production.min.js"></script>

<div id="app"></div>

Disclaimer: The addition of + 1 in {i + divider * j + 1} is purely for visual representation purposes. I hope this solution meets your requirements. Cheers!

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

Is it possible to make the dropdown menu content appear above instead of below?

I am exploring the possibility of using an accordion within a bootstrap dropdown that opens in an upward direction ("dropup") to have the menu expand upwards. In my attempts, I successfully integrated the "accordion" inside the dropdown, as illustrated in ...

utilizing django with sizeable jquery datagrids causes performance issues

I am currently facing an issue with rendering a large dataset (20k rows) in a jQuery datatable within a Django project. The rendering process is very slow, and I am looking for alternative approaches to speed it up. One suggestion I came across is using de ...

Replacing the onEnter hook in React-Router v4

I am currently in the process of developing a basic react-redux application that stores student and campus information on the backend. Previously, OnEnter was functioning properly in this setup, but it is no longer available in the new react-router version ...

Tips for retrieving information from an API and displaying it in a table

I'm struggling to retrieve data (an array of objects) from an API using a Token and display them in a table using Material-UI. However, I keep encountering the following error: Uncaught (in promise) SyntaxError: Unexpected token 'A', "Access ...

Reactjs Component Variable is immutable and cannot be edited

I am experiencing issues with the following code. Any advice would be appreciated. parent = react.createClass({ getInitialState: function(){ return {tags:{}}; }, render:function(){ return <child update={this.updateState ...

My program is throwing an error due to invalid JSON format

Snippet of code: var data = $.parseJSON(data); Error message: Encountered Invalid JSON: {times: [{'9:30am','10:00am','10:30am','11:00am','11:30am','12:00pm','12:30pm','1:00pm&apo ...

Is it possible to jest at a module function that is both exported and utilized within the same module?

Just diving into unit testing and learning about spies, stubs, and mocks. I've been trying to test the verify method in password.js as shown in the code snippet below. However, I'm having trouble creating a stub for the hash function within the ...

Converting RGBA to Hex Color Code with Javascript: A Step-by-Step Guide

I attempted to change the rgba color representation to hexadecimal, but I encountered difficulty in converting the opacity value while successfully converting the remaining colors. Here is the snippet of my code: var colorcode = "rgba(0, 0, 0, 0.74)"; ...

What is a way to simulate division using only multiplication and whole numbers?

The issue at hand: The stack-building API that I'm currently using in rapidweaver has limitations when it comes to division or floats, making it challenging to perform certain mathematical operations. Insights into the API's rules: This partic ...

Submenu malfunctioning in Internet Explorer and Chrome, but functioning properly in Firefox and Opera

I've been working on some HTML code that runs perfectly in FF and Opera, and even in IE for my friend. However, I'm having trouble getting the output to display properly in Chrome. Any ideas why this might be happening? <html> <head> ...

Different ways to pass a component as a prop and display it based on certain conditions?

I'm currently working on a component that takes an ID number, checks its existence in the database, and renders a component if it's found. I need assistance with structuring this logic properly. Any guidance would be greatly appreciated. function ...

Assign the default value to the document title

Just a simple question.. If I set an alert to change the document title to "ALERT" temporarily, is there an easy way to change it back afterward? Or will I need to assign an ID to the link tags to reset the title to that ID value? Keep in mind this script ...

What is the best way to determine the dimensions of a KonvaJs Stage in order to correctly pass them as the height/width parameters for the toImage function

Currently, I am using KonvaJs version 3.2.4 to work with the toImage function of the Stage Class. It seems that by default, toImage() only captures an image of the visible stage area. This is why there is a need to provide starting coordinates, height, and ...

jquery hover effect not functioning properly

I have a question regarding my jquery mobile application. I am trying to implement a hover effect on items with the class grid-item, where the width and height change simultaneously in an animation. Here is the code snippet I am using: $('.grid-i ...

I am having trouble getting Highcarts to load the JSON data

I am currently in the process of utilizing Highcharts to generate a chart. The JSON output I have is in standard format and was generated using PHP's json_encode() function. Below is the JSON output: [["2015-07-13 16:41:05","3"],["2015-08-15 16:41:05 ...

Issue with the Select All checkbox functionality in an asp.net mvc project

https://i.sstatic.net/Y5ml2.png Here, I manually select checkboxes and press the sync button. When I do this individually, it works properly. However, if I press the select all button, all the checkboxes are selected but the sync process does not occur. ...

Generate a unique JavaScript object without any redundancy

I am in the process of creating a JavaScript object that needs to be processed through a PHP API. The structure should resemble the following: [{ 'targetId': 'roof', 'color': 'red' }, { 'targetId': ...

Java - processing calculations at a slower pace

My current code runs very slowly, taking a long time to process and complete the calculations. I am wondering if there are any ways to optimize it for better performance and efficiency? int n = 25; int len = (int) Math.pow(2, n); String[][] BinaryNumbers ...

Is it recommended to update my peer dependencies when upgrading my RN version?

Recently, I took on the task of updating my old project from RN 0.61.x to 0.70.x and react 16 to react 18. During this process, I encountered a challenge with dependencies that were tied to older versions of React Native in their peer dependencies. This is ...

What is the best way to maintain an ongoing sum of multiple values using bacon.js?

Experimenting with the power of bacon.js. I want to maintain a dynamic total of values from a set of text inputs. The example on the github page utilizes the .scan method along with an adding function, which functions well for simple increment and decremen ...