0

In AngularJS is possible sort an array like this ng-repeat="user in users | orderBy: order" and i need to know how do this in ReactJS, here is an exemple of this in AngularJS

const myApp = angular.module('myApp', [])
myApp.controller('myAppController', ['$scope', $scope => {
  $scope.users = [
    { name: 'Maria', age: 16, color: 'red' },
    { name: 'Mike', age: 18, color: 'black' },
    { name: 'John', age: 23, color: 'green' },
    { name: 'Liza', age: 21, color: 'yellow' }
  ]
  $scope.order = 'name'
  $scope.orderBy = orderBy => $scope.order = orderBy
}])
<script src="https://cdnjs.cloudflare.com/ajax/libs/angular.js/1.7.5/angular.min.js"></script>
<table ng-app="myApp" ng-controller="myAppController">
  <tr>
    <th ng-click="orderBy('name')">Name</th>
    <th ng-click="orderBy('age')">Age</th>
    <th ng-click="orderBy('color')">Color</th>
  </tr>
  <tr ng-repeat="user in users | orderBy: order">
    <td>{{user.name}}</td>
    <td>{{user.age}}</td>
    <td>{{user.color}}</td>
  </tr>
</table>

2

1 Answer 1

2

React.js is a plain javascript.
You should use Array.prototype.sort.
Created stackblitz for you.

import React, { Component } from 'react';
import { render } from 'react-dom';
import Hello from './Hello';
import './style.css';

class App extends Component {
  constructor() {
    super();
    this.state = {
      name: 'React',
      order: 'name',
      users: [
        { name: 'Maria', age: 16, color: 'red' },
        { name: 'Mike', age: 18, color: 'black' },
        { name: 'John', age: 23, color: 'green' },
        { name: 'Liza', age: 21, color: 'yellow' }
      ]
    };
    this.sort = this.sort.bind(this); 
    this.setOrder = this.setOrder.bind(this); 
  }

  setOrder(e) {
    const order = e.target.dataset.order;

    this.setState({order});
  }

  sort(a, b) {
    if (!this.state.order) return 0;
    if(a[this.state.order] < b[this.state.order]) { return -1; }
    if(a[this.state.order] > b[this.state.order]) { return 1; }
    return 0;
  }

  render() {
    return (
      <div>
        <button data-order='name' onClick={this.setOrder}>by name</button>
        <button data-order='color' onClick={this.setOrder}>by color</button>
        {this.state.users.sort(this.sort).map(user => <div>name: {user.name}, color: {user.color}</div>)}
      </div>
    );
  }
}

render(<App />, document.getElementById('root'));
Sign up to request clarification or add additional context in comments.

Comments

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.