Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Inserting an element after every 'X' React components

I have a React component that renders a list of items into three columns using Bootstrap's col col-md-4 styles. However, I need to insert a clearfix div after every third element to ensure that the next 'row' of elements displays in the correct place.

My current render code looks like this:

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

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

Item simply renders a div with the col classes, containing the passed-in content:

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

My current workaround is to pass the index of the Item in as a prop, and then apply the clearfix class to the Item if the index is a multiple of 3, but this feels a bit hackish to me and I would prefer a separate div to allow me to only show the clearfix on the required viewport size (using Bootstrap's visible-* classes).

I'm sure there must be a more elegant way to solve this problem than the one I've come up with. Any suggestions are appreciated.

like image 491
AdmiralFailure Avatar asked Dec 15 '22 07:12

AdmiralFailure


1 Answers

You could iterate your array and add a <div/> 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>
  );
}
like image 147
Florian Cargoet Avatar answered Dec 30 '22 16:12

Florian Cargoet