Home > OS >  Create a React componenent by grouping an array by index range in JS
Create a React componenent by grouping an array by index range in JS

Time:10-26

Let's say I've an array like this:

const a = [0,1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17, 18, 19];

I want to return a react component containing the values of a, taking them in group of 10 elements. So the expected output would be:

<MyReactBox>
   <span>The first ten</span>
   <span>0, 1, 2, 3, 4, 5, 6, 7, 8, 9</span>
   <span>The last ten</span>
   <span>10, 11, 12, 13, 14, 15, 16, 17, 18, 19</span>
</MyReactBox>

What would be the best way to do this?

CodePudding user response:

class TodoApp extends React.Component {
  constructor(props) {
    super(props)
  }

  render() {
    const getCustom = (rangeFirst, rangeLast) => {
    return(
  <div>
     <span>The first ten</span>
     <span>{rangeFirst}</span>
     <span>The last ten</span>
     <span>{rangeLast}</span>
  </div>
  );};
  const a = [0,1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17, 18, 19];
    return (
     <div>
     <span>{getCustom(a.slice(0,10).join(", "), a.slice(-10).join(", "))}</span>
    
   </div>
    )
  }
}

ReactDOM.render(<TodoApp />, document.querySelector("#app"))
<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>
<iframe name="sif1" sandbox="allow-forms allow-modals allow-scripts" frameborder="0"></iframe>

here, replace this with your component-

<div>
     <span>The first ten</span>
     <span>{rangeFirst}</span>
     <span>The last ten</span>
     <span>{rangeLast}</span>
  </div>

CodePudding user response:

One way is to build dynamically based on array size using the slice and Array.from methods. This should work for any size of array. (just labels array to update to customize the title)

const a = [0,1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17, 18, 19];

const labels = ['first', 'second', 'third', 'fourth']

const Component = () => {
  const len = Math.ceil(a.length / 10);
  return (
    <div>
      {Array.from({ length: len }, (_, idx) => (
        <div key={`The ${(idx 1) === len ? 'last' : labels[idx] || idx} Ten : `}>
          <span>{`The ${(idx 1) === len ? 'last' : labels[idx]} Ten : `}</span>
          <span>{a.slice(idx * 10, idx * 10   10).join(', ')}</span>
        </div>
      ))}
    </div>
  );
};

ReactDOM.render(<Component />, document.getElementById("app"));
<script crossorigin src="https://unpkg.com/react@17/umd/react.development.js"></script>
<script crossorigin src="https://unpkg.com/react-dom@17/umd/react-dom.development.js"></script>

<div id="app"></div>
<iframe name="sif2" sandbox="allow-forms allow-modals allow-scripts" frameborder="0"></iframe>

  • Related