Placing a new item following each occurrence of 'X' in React components

Currently, I am working with a React component that uses Bootstrap's col col-md-4 styles to render a list of items in three columns. However, I am facing an issue where I need to add a clearfix div after every third element to ensure proper display of the next 'row' of elements.

This is how my current rendering code looks:

render() {
  var resultsRender = $.map(this.state.searchResults, function (item) {
    return <Item Name={ item.Name } Attributes={ item.Attributes } />;
  }

  return (
    <div>{ resultsRender }</div>
  );
}

The Item component simply renders a div with the necessary classes:

render() {
  return(
    <div className='col col-md-4'>
      ...content here...
    </div>
  );
}

My current solution involves passing the index of each Item as a prop and applying the clearfix class if the index is a multiple of 3. However, I feel like this approach is a bit hacky and I would prefer a cleaner method using a separate div to conditionally show the clearfix based on viewport size using Bootstrap's visible-* classes.

If anyone has suggestions for a more elegant solution to this problem, I would greatly appreciate it.

Answer №1

To enhance the presentation of your array, consider inserting a <div/> after every 3 items:

render() {
  var items = $.map(this.state.searchResults, function (item) {
    return <Item Name={ item.Name } Attributes={ item.Attributes } />;
  }

  var resultsRender = [];
  for (var i = 0; i < items.length; i++) {
    resultsRender.push(items[i]);
    if (i % 3 === 2) {
      resultsRender.push(<div className="clearfix" />);
    }
  }

  return (
    <div>{ resultsRender }</div>
  );
}

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

Issue with jQuery DataTable displaying content from the beginning of its text is not visible

I have utilized a jQuery DataTable to exhibit the roster of employees in a store. The framework of the table is as follows: <table class="gridTableSummary hover pretty cell-border" id="summarytable" cellspacing="0"> <thead class="col-h ...

The loop within a loop is causing excessive lag and is on the verge of crashing the

I need help with optimizing the performance of my app that retrieves json data. The json file contains nearly one thousand words structured like this: {"THEMES":{"THEME1":["ITEM1","ITEM2","ITEM3"],"THEME2":["ITEM1",...]...}} The size of the file is aroun ...

Redux export does not complete correctly unless brackets are used

I'm trying to understand why the main JS file is having trouble importing todo from './actions' without brackets, while there are no issues with importing todos from './reducers'. Main js-file: import { createStore } from 'r ...

Is it possible to use JavaScript to save and preserve the current state of a webpage?

I'm looking for a way to retrieve the entire content of a webpage using JavaScript and then send it to a server script for saving. This action should be triggered after the user has made some changes to the page using AJAX and other JavaScript tools. ...

Pattern Matching for Website Addresses

I'm having trouble with the regular expression I'm using to validate URLs. The expression is /\b(http|https)?(:\/\/)?(\S*)\.(\w{1,45})/ig It seems that the regular expression only works for URLs up to a certain leng ...

Laravel 5.2 is designed to exclusively extract numerical values from AJAX post requests

When using AJAX to submit my form, I encountered an issue where only the numeric values were being passed through. Even though all variables appeared populated before submitting the form, only the numeric ones made it to the controller. AJAX: function ap ...

"Encountering an issue with supabase.auth.getUser() when implementing a vue-router route guard

My Vue application project involves integrating Supabase authentication. In one of the route guards within the router file, I used supabase.auth.getUser() to determine the user's login status and control the execution flow based on that condition: // ...

Update the ngModel value once input validation has been successfully validated

My input is defined as shown below <input id="xInputControl" name="xInputControl" type="text" xInput class="form-control" [(ngModel)]="x" #validated="ng ...

I am experiencing an issue where the jquery sleep function is not being executed during

I currently have an Ajax request that is awaiting a response from another process. function checkProcess() { var flag = 0; while (flag === 0) { $.ajax({ url: "cs/CheckForProcess", async: false, success: ...

Ways to display JSON in a structured format on an HTML page

Is there a way to display JSON in a formatted view on my html page? The JSON data is coming from a database and I want it to be displayed neatly like the following example: { "crews": [{ "items": [ { "year" : "2013", "boat" ...

The server-side PHP script may not always successfully respond to an Ajax call from the client

Whenever I try to access my index.html site, there are times when the Ajax request is made to call the PHP on the server in order to display the dynamic content. But for some reason, it only works intermittently when I manually refresh the page using the a ...

Displaying time text in input element due to browser bug

I am faced with a perplexing puzzle that has left me scratching my head. Here are two seemingly identical pieces of javascript code, but one behaves unexpectedly (take note of the Console.Log): Updates the UI once, then abruptly stops updating: http://js ...

Dropzone.js only allows one audio file and one image thumbnail file to be uploaded simultaneously

Is there a way to limit the types of files that can be uploaded through Dropzone.js? Specifically, I want to restrict users to uploading only one image and one audio file. ...

Create a variety of unique objects on the canvas without any repetition or unwanted overlapping

Is there a way to generate objects on a map in a HTML5 Canvas without them overlapping or occupying the same space? I tried checking inside an array to see if the next 20 values are already taken to prevent overlapping, but it didn't work as expected ...

Looking to add a dropdown feature to my current main navigation bar

I've been struggling to add a drop-down menu to my website's main menu. Every time I try, something goes wrong - sometimes the menu appears inline, other times it completely messes up the layout. Here is the HTML code snippet: <ul class="m ...

The ElementNotInteractableException was thrown because the element could not be accessed via the keyboard when trying to input text into the FirstName field on Facebook

The issue is as follows: Exception encountered in thread "main" org.openqa.selenium.ElementNotInteractableException: Element is not accessible via keyboard Here is the code snippet: System.setProperty("webdriver.gecko.driver"," ...

"Encountering a unique glitch in jQuery: Un

Targeting dynamic divs is my current focus, and I have created the following code for that purpose: if ($("#" + selector_name "#" + name + add_count).size() == 0) { var p = "<div id = '" + name + add_count + "' class='progressbar&apo ...

Restangular: Avoiding empty parameter being passed

In my AngularJS application using RestAngular, I have the following controller method: $scope.findFriend = function (name, type, limit) { return FriendSearch.getList({ name: name, type: type, limit: limit ...

Application crashes while executing reactDOM.render()

I've been attempting to run an existing React/Node application on my local machine. Unfortunately, it keeps failing at the index.js file specifically at the line where reactDOM.render() is called. Module parse failed: C:\Users\dan\Docu ...

What is the process of displaying text within a link?

I have a basic webpage where I want the text to display from a link. Here is my website: <!DOCTYPE html> <html lang="en"> <head> <meta charset="utf-8" /> <title>Encyclopedia</title> <link href="test.css" re ...