Skip to content

Instantly share code, notes, and snippets.

@aerrity
Created February 1, 2019 16:47
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save aerrity/7d6a91fbabbc34ac8d4c3d23d29f6884 to your computer and use it in GitHub Desktop.
Save aerrity/7d6a91fbabbc34ac8d4c3d23d29f6884 to your computer and use it in GitHub Desktop.
React - Searching & sorting a list of random users
import React, { Component } from "react";
import axios from "axios";
class App extends Component {
constructor(props) {
super(props);
this.state = { users: [], searchTerm: '', alphabetical: 'az' };
this.handleChange = this.handleChange.bind(this);
}
componentDidMount() {
axios
.get("https://randomuser.me/api/?results=60")
.then(response => {
console.log(response.data.results);
this.setState({ users: response.data.results });
})
.catch(error => {
console.log(error);
});
}
handleChange(event) {
const target = event.target;
const value = target.type === 'checkbox' ? target.checked : target.value;
const name = target.name;
this.setState({
[name]: value
});
}
render() {
let sortedUsers;
if (this.state.alphabetical === "az") {
console.log("sort");
sortedUsers = this.state.users.sort((a, b) =>
a.name.first > b.name.first ? 1 : -1
);
} else {
sortedUsers = this.state.users.sort((a, b) =>
a.name.first < b.name.first ? 1 : -1
);
}
let filteredUsers = sortedUsers;
if (this.state.searchTerm)
filteredUsers = this.state.users.filter(u =>
u.name.first.startsWith(this.state.searchTerm)
);
const userNames = filteredUsers.map(u => {
return <User key={u.email} name={u.name.first} age={u.dob.age} />;
});
return (
<div>
<form onSubmit={this.handleSubmit}>
<label>
Search for user:
<input
type="text"
name="searchTerm"
value={this.state.searchTerm}
onChange={this.handleChange}
/>
</label>
<input type="submit" value="Submit" />
</form>
<select
name="alphabetical"
value={this.state.alphabetical}
onChange={this.handleChange}
>
<option selected value="az">
A to Z
</option>
<option value="za">Z to A</option>
</select>
{userNames}
</div>
);
}
}
class User extends Component {
render() {
return (
<div>
<h2>{this.props.name}</h2>
<h3>{this.props.age}</h3>
</div>
);
}
}
export default App;
@bumlev
Copy link

bumlev commented Nov 3, 2022

tell me the way to get github users

@aerrity
Copy link
Author

aerrity commented Nov 3, 2022

This code hasn't been maintained for several years so may no longer function.
Can you elaborate on your query?

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment