Last active
August 5, 2020 04:24
-
-
Save Alezco/700f6cfe32a0b7bb2c65fc39923cfd20 to your computer and use it in GitHub Desktop.
User list using a React Typescript functional component
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import React, { FC, useCallback, useEffect, useMemo, useState } from "react"; | |
type UserListProps = { | |
title: string; | |
}; | |
type User = { | |
firstName: string; | |
lastName: string; | |
}; | |
const UserList: FC<UserListProps> = ({ title }) => { | |
const [isVisible, setIsVisible] = useState(true); | |
const [users, setUsers] = useState<User[]>([]); | |
const toggleVisibility = useCallback(() => setIsVisible(!isVisible), [setIsVisible, isVisible]); | |
const onKeyDown = useCallback( | |
({ key }: KeyboardEvent) => { | |
if (key === "t") { | |
toggleVisibility(); | |
} | |
}, | |
[toggleVisibility] | |
); | |
const newUsers = useMemo( | |
() => [ | |
{ | |
firstName: "Bruce", | |
lastName: "Banner", | |
}, | |
{ | |
firstName: "Peter", | |
lastName: "Parker", | |
}, | |
{ | |
firstName: "Stephen", | |
lastName: "Strange", | |
}, | |
] as User[], | |
[] | |
); | |
useEffect(() => { | |
setUsers(newUsers); | |
}, [setUsers, newUsers]); | |
useEffect(() => { | |
document.body.addEventListener("keydown", onKeyDown, false); | |
return () => document.body.removeEventListener("keydown", onKeyDown, false); | |
}, [onKeyDown]); | |
return ( | |
<div> | |
<h3>{title}</h3> | |
<button onClick={toggleVisibility}>Toggle visibility</button> | |
{isVisible && ( | |
<ul> | |
{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