Home > Mobile >  Avoid looping multiple times the same array in React and JSX
Avoid looping multiple times the same array in React and JSX

Time:09-28

Suppose I have this array of objects:

const itensArray = [
  { "year": 2000, "text": "Lorem ipsum" }, 
  { "year": 2010, "text": "Hello World" },
  { "year": 2020, "text": "This is the end" }
];

Suppose it will be used to create elements in an timeline HTML structure, where the elements are separeted:

<div className="timeline-years">
  <ul>{ yearsList }</ul>
</div>
<div className="timeline-texts">
  <ul>{ textList }</ul>
</div>

I know one way to achieve this is to loop the same array two times:

const yearsList = itensArray.map(item =>
  <li>{ item.year }</li>
);

const textList = itensArray.map(item =>
  <li>{ item.text }</li>
);

How can I achieve the same result in one map only and using React and JSX?

The code below is wrong, but it illustrates what I want:

itensArray.map(item =>
  let yearsList = <li>{ item.year }</li>
  let textList = <li>{ item.text }</li>
);

Thanks!

CodePudding user response:

Dont afraid loop twice over one array, because data you should display in different places. You may preloop your array and assign your bunch of li elements as a const and put them in react fragments:

import React from 'react';
const itensArray = [
  { year: 2000, text: 'Lorem ipsum' },
  { year: 2010, text: 'Hello World' },
  { year: 2020, text: 'This is the end' },
];
function Component() {
  const yearsList = (
    <>
      {itensArray.map((item) => (
        <li>{item.year}</li>
      ))}
    </>
  );
  const textList = (
    <>
      {itensArray.map((item) => (
        <li>{item.text}</li>
      ))}
    </>
  );

  return (
    <>
      <div className="timeline-years">
        <ul>{yearsList}</ul>
      </div>
      <div className="timeline-texts">
        <ul>{textList}</ul>
      </div>
    </>
  );
}

export default Component;

CodePudding user response:

If your target is to achieve this using only one loop then it could be a solution.

export default function App() {
  const itensArray = [
    { "year": 2000, "text": "Lorem ipsum" }, 
    { "year": 2010, "text": "Hello World" },
    { "year": 2020, "text": "This is the end" }
  ];
  const yearsList  = []
  const textList = []

  itensArray.forEach((item)=>{
    yearsList.push(<li>{ item.year }</li>)
    textList.push(<li>{ item.text }</li>)
  })
  console.log(yearsList)
  return (
    <div className="App">
      <ul>{yearsList}</ul>
      <ul>{textList}</ul>
    </div>
  );
}
  • Related