user12584890
user12584890

Reputation: 1

Sorting alphabetically in reactJS

I am trying to sort alphabetically the list of users in my app, adding a button in ReactJS.

The only way I can get this working is passing props, but I know this must not be done because props should not be mutated. Need some help to understand what I am doing wrong. This is my Users component:

import React from "react";
import { Route, Link } from "react-router-dom";
import User from "./User";

class Users extends React.Component {
  state = {
    sort: "asc"
  };

  toggleSort = () => {
    const { users } = this.state;
    this.props.users.sort((a, b) => a.name.localeCompare(b.name));
    this.setState({ users });
  };

  render() {
    const { users } = this.state;

    return (
      <div>
        {this.props.users.map(user => (
          <li key={user.id}>
            <Link to={`/users/${user.id}`}>{user.name}</Link>
          </li>
        ))}
        <button onClick={() => this.toggleSort(users)}>Sort</button>

        <Link to={`/users/new`} />
      </div>
    );
  }
}

export default Users;

This is the only way I can get my sort button to work, but passing the props... Any help? I am pretty new to React

Thanks!

Upvotes: 0

Views: 6645

Answers (2)

Joshua Obritsch
Joshua Obritsch

Reputation: 1293

If you don't want to mutate the props then create a new variable:

toggleSort = () => {
  const newUsers = { ...this.props.users };
  newUsers.sort((a, b) => a.name.localeCompare(b.name));
  this.setState({ users: newUsers });
};

and in your render function:

{this.state.users.map(user => (
  <li key={user.id}>
    <Link to={`/users/${user.id}`}>{user.name}</Link>
  </li>
))}

Upvotes: 2

import React from "react";
import { Route, Link } from "react-router-dom";
import User from "./User";

class Users extends React.Component {

  // set users when component mounted.
  componentDidMount () {
    this.setState({
      users: this.props.users
    });
  }

  state = {
    users: [],
    sort: "asc"
  };

  toggleSort = () => {
    const { users } = this.state;
    let newUsers = users.sort((a, b) => a.name.localeCompare(b.name));
    this.setState({ users: newUsers });
  };

  render() {
    const { users } = this.state;

    return (
      <div>
        {users.map(user => (
          <li key={user.id}>
            <Link to={`/users/${user.id}`}>{user.name}</Link>
          </li>
        ))}
        <button onClick={() => this.toggleSort(users)}>Sort</button>

        <Link to={`/users/new`} />
      </div>
    );
  }
}

export default Users;

Upvotes: 0

Related Questions