In ReactJS, getting the last item in an array is not specific to React itself but is a basic JavaScript operation. You can achieve this using various methods:
Using Array Index: You can use the index -1
to access the last item in the array.
import React from 'react';
class LastItemInArray extends React.Component {
render() {
const array = [1, 2, 3, 4, 5]; // Your array here
const lastItem = array[array.length - 1];
return (
<div>
<p>Last Item: {lastItem}</p>
</div>
);
}
}
export default LastItemInArray;
Using Array.prototype.slice()
: You can use the slice
method to create a new array containing the last element and then access it.
import React from 'react';
class LastItemInArray extends React.Component {
render() {
const array = [1, 2, 3, 4, 5]; // Your array here
const lastItem = array.slice(-1)[0];
return (
<div>
<p>Last Item: {lastItem}</p>
</div>
);
}
}
export default LastItemInArray;
Using Array.prototype.pop()
: You can also use the pop
method to remove and return the last element from the array. Note that this method will modify the original array.
import React from 'react';
class LastItemInArray extends React.Component {
render() {
let array = [1, 2, 3, 4, 5]; // Your array here
const lastItem = array.pop();
return (
<div>
<p>Last Item: {lastItem}</p>
</div>
);
}
}
export default LastItemInArray;
Choose the method that best fits your needs. If you want to keep the original array intact, using the index or slice
method is recommended. If you don’t need the original array afterward, you can use the pop
method.