0

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

3 Answers 3

1

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>
))}
Sign up to request clarification or add additional context in comments.

Comments

1

Use splice and remove the inner {} brackets as .map() needs to return values to work.

The splice() method adds/removes items to/from an array, and returns the removed item(s).

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

Comments

0

You should return the value by using return keyword.

2 Comments

If you could please edit the code snippet, that'd be great
@velsonjr Welcome

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.