Search code examples
reactjsconditional-renderinges6-map

Issue with rendering React JSX using if conditional inside map


case 1) I am trying to conditionally render using map and a ternary operator. Here I am iterating over an array of objects and then render only first six of them. Trying to achieve the same, but it does not seem like working.

Help would be appreciated

OBJECT

const recentEventsData = [
  { key: "01", text: "AAA", timestamp: "11:52:27:02 02-11-2019" },
  { key: "02", text: "BBB", timestamp: "11:52:29:02 02-11-2019" },
  { key: "03", text: "CCC", timestamp: "11:52:30:02 02-11-2019" }
];

Inside render()

{
  recentEventsData.map((data, index) => {
    {
      index < 6 ? (
        <div key={index}>
          //Want the transformed output here , that is fourth value from object
          <p>{data.text}</p>
          <p>{data.timestamp}</p>
          <hr />
        </div>
      ) : null;
    }
  });
}

Solution

  • You only need to use {} inside JSX when you want to inject a JavaScript expression, so inside the function given to map there is no need to create a new block.

    Since you have given the function a body, you also need to explicitly return the result.

    {recentEventsData.map((data, index) => {
      return index < 6 ? (
        <div key={index}>
          <p>{data.text}</p>
          <p>{data.timestamp}</p>
          <hr />
        </div>
      ) : null;
    })}
    

    Instead of checking the index and returning null for the rest of the elements, you can instead slice out the elements you are interested in before using map.

    {recentEventsData.slice(0, 6).map((data, index) => (
      <div key={index}>
        <p>{data.text}</p>
        <p>{data.timestamp}</p>
        <hr />
      </div>
    ))}