-
Notifications
You must be signed in to change notification settings - Fork 0
/
gallery.tsx
48 lines (35 loc) · 1.26 KB
/
gallery.tsx
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
import React, { useState } from "react";
import ReactDOM from "react-dom";
import { createNanoEvents, createUseEvent } from "react-simple-events";
interface GalleryEvents {
selected(item: string): void;
}
const galleryEmitter = createNanoEvents<GalleryEvents>();
const useGalleryEvent = createUseEvent(galleryEmitter);
const items = ["Apple", "Book", "Tree", "Sun", "Sky"];
function App() {
return (
<>
<ChosenItem />
{items.map((item, idx) => <Item key={idx} item={item} />)}
</>
);
}
function ChosenItem() {
const [item, setItem] = useState<null | string>(null);
useGalleryEvent("selected", (item) => setItem(item), [setItem]);
return item !== null ? <p>You've selected: {item}</p> : <p>Select an item!</p>;
}
function Item({ item }: { item: string }) {
const [selected, setSelected] = useState(false);
useGalleryEvent("selected", (selectedItem) => {
const shouldBeSelected = item === selectedItem;
if (selected !== shouldBeSelected) {
setSelected(shouldBeSelected);
}
}, [selected, setSelected]
);
const selectThisItem = () => galleryEmitter.emit("selected", item);
return <p onClick={selectThisItem}>{item} {selected && "(Selected)"}</p>;
}
ReactDOM.render(<App />, document.getElementById("root"));