Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to reverse an Array in React [duplicate]

How do I reverse an array in react? I tried using this.state.data.maps.reverse but it ain't working. Thanks in advance!

import React, { Component } from 'react';

export default class Slideshows extends Component {
    constructor(){
        super();
        this.state = {
            data:[
                { "id": "1", "name": 'Robert', "age": "21" },
                { "id": "2", "name": 'Sam', "age": "33" },
                { "id": "3", "name": 'Jerry', "age": "42" },
            ]
        }
    }
    render() {
        const reverseData = this.state.map((data, i) => {
            return (
                <li> {data.name} | {data.age} </li>
            )
        })
        return (
            <ul>
                {reverseData}
            </ul>
        )
    }
}
like image 478
William Avatar asked Apr 12 '18 12:04

William


2 Answers

You should get data from your state first, then apply reverse() on it, then map reversed array:

    const reverseData = this.state.data.reverse().map((data, i) => {
        return (
            <li> {data.name} | {data.age} </li>
        )
    })
like image 95
asiniy Avatar answered Oct 07 '22 00:10

asiniy


This question has already been addressed here, please visit this link below:

REACT Reverse an array

like image 43
Mustajeeb ur Rehman Avatar answered Oct 07 '22 01:10

Mustajeeb ur Rehman