0

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!

2 Answers 2

2

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>
))}
Sign up to request clarification or add additional context in comments.

Comments

0

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;

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.