Skip to content

Instantly share code, notes, and snippets.

@stevebrownlee
Last active July 5, 2019 21:39
Show Gist options
  • Save stevebrownlee/f288c3d8c64c93fe61a986a202511288 to your computer and use it in GitHub Desktop.
Save stevebrownlee/f288c3d8c64c93fe61a986a202511288 to your computer and use it in GitHub Desktop.
React component to display a list of Animal components, and a AnimalDialog component
import React, { useState, useContext, useEffect, useRef } from "react"
import Animal from "./Animal"
import AnimalDialog from "./AnimalDialog"
import { AnimalContext } from "../providers/AnimalProvider"
import useModal from "../../hooks/ui/useModal"
import "./AnimalList.css"
export default (props) => {
const { toggleDialog, modalIsOpen } = useModal("#dialog--animal")
const [currentAnimal, setCurrentAnimal] = useState({treatments:[]})
const { animals, search } = useContext(AnimalContext)
const showTreatmentHistoryDialog = (animal) => {
setCurrentAnimal(animal)
toggleDialog()
}
useEffect(() => {
const handler = e => {
// Close dialog when ESC is pressed
if (e.keyCode === 27) {
if (modalIsOpen) {
toggleDialog()
}
}
}
window.addEventListener("keyup", handler)
return () => window.removeEventListener("keyup", handler)
}, [toggleDialog])
return (
<React.Fragment>
<AnimalDialog
toggleDialog={toggleDialog}
animal={currentAnimal} />
<ul className="animals">
{animals.map(animal =>
<Animal
showTreatmentHistory={showTreatmentHistory}
key={animal.id}
animal={animal} />)}
</ul>
</React.Fragment>
)
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment