Skip to content

Instantly share code, notes, and snippets.

@Alezco
Last active April 22, 2020 08:44
Show Gist options
  • Save Alezco/8102b1f98a96512a583a3def3f8826e7 to your computer and use it in GitHub Desktop.
Save Alezco/8102b1f98a96512a583a3def3f8826e7 to your computer and use it in GitHub Desktop.
User list using a ReactJS class component
import React from "react";
class UserList extends React.Component {
constructor(props) {
super(props);
this.state = {
isVisible: true,
users: [],
};
this.toggleVisibility = this.toggleVisibility.bind(this);
}
fillUsers() {
const users = [
{
firstName: "Bruce",
lastName: "Banner",
},
{
firstName: "Peter",
lastName: "Parker",
},
{
firstName: "Stephen",
lastName: "Strange",
},
];
this.setState({ users });
}
toggleVisibility() {
this.setState({ isVisible: !this.state.isVisible });
}
onKeyDownHandler(event) {
if (event.key === "t") {
this.toggleVisibility();
}
}
componentDidMount() {
this.fillUsers();
document.body.addEventListener(
"keydown",
(event) => this.onKeyDownHandler(event),
false
);
}
componentWillUnmount() {
document.body.removeEventListener(
"keydown",
(event) => this.onKeyDownHandler(event),
false
);
}
render() {
return (
<div>
<h3>{this.props.title}</h3>
<button onClick={this.toggleVisibility}>Toggle visibility</button>
{this.state.isVisible && (
<ul>
{this.state.users.map((user, index) => (
<li key={index}>{`${user.firstName} ${user.lastName}`}</li>
))}
</ul>
)}
</div>
);
}
}
export default UserList;
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment