1

I have an array of data that is returned to me from a CMS. I map over each item and return a component with the corresponding data. However, I need to target the last item in the .map function in the render method as the last item needs some modification.

How would I do this?

return (
  <div>
    {data.body.map((item, i) => {
      console.log(i);
      if (item.type === 'button') {
        return <ButtonComponent color="ffffff" bgColor="4C319D" text={item.text} textAlign="left" id={item.id} />
      }
    })}
  </div>
)
1

2 Answers 2

7

Test the index against the length of the array.

const array = ['a', 'b', 'c', 'd'];

const mapped = array.map(
    (value, index, array) => {
        if (array.length - 1 === index) {
            console.log(`${value} is the last item in the array`);
            return `-->${value.toUpperCase()}<--`;  
        } else {
            return value.toLowerCase();  
        }
    } 
);

console.log({mapped});

Sign up to request clarification or add additional context in comments.

Comments

2

generally for access to the last item in array you can use this Formula:

const myArray = [1,2,3,4];

myArray[myArray.length - 1] // return 4.

and in your code you can use this way:

<div>
      {data.body.map((item, i) => {
        console.log(i);
        if (item.type === 'button') {
          return <ButtonComponent color="ffffff" bgColor="4C319D" text={item.text} textAlign="left" id={item.id} />
        }
        const lastItem = data.body[data.body.length - 1]
      })}


    </div>

1 Comment

and also you must use key={item.id} instead of id={item.id} in <ButtonComponent />

Your Answer

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