Inserting an element after every 'X' React components

≯℡__Kan透↙ 提交于 2021-01-27 13:17:48

问题


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.


回答1:


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>
  );
}


来源:https://stackoverflow.com/questions/36619418/inserting-an-element-after-every-x-react-components

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!