/
App.js
108 lines (96 loc) · 2.82 KB
/
App.js
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
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
import React, { useState, useMemo } from 'react';
import cn from 'clsx';
import { housesData, charactersData } from './staticData';
import './styles.css';
function Header(props) {
console.log('render: Header');
const { children } = props;
return (
<header className="app-header">
<h1 className="app-name">Potter World</h1>
{children}
</header>
);
}
function Picker(props) {
console.log('render: Picker');
const { activeHouseId, onChange } = props;
return (
<div className="house-picker">
<h3>Filter by House</h3>
<ul className="house-list">
{housesData.map((house) => (
<li key={house.id}>
<button
className={cn('house', activeHouseId === house.id && 'active')}
onClick={(event) => onChange(house.id, event)}
>
<span>{house.name}</span>
<img src={house.imageUrl} alt={house.name} className="house-logo" />
</button>
</li>
))}
</ul>
</div>
);
}
function Table(props) {
console.log('render: Table');
const { charactersList } = props;
return (
<table className="table">
<thead className="table-head">
<tr className="table-row">
<th className="table-cell">Name</th>
<th className="table-cell">House</th>
</tr>
</thead>
<tbody>
{charactersList.map((character) => (
<tr key={character.name}>
<td className="table-cell">{character.name}</td>
<td className="table-cell">{character.house}</td>
</tr>
))}
</tbody>
</table>
);
}
const OptimizedTable = React.memo(Table);
function filterByHouse(houseId) {
return charactersData.filter((character) => {
if (houseId === 'all') {
return true;
}
return character.houseId === houseId;
});
}
function App() {
console.log('render: App');
const [stateTheme, setStateTheme] = useState('dark');
const [stateActiveHouseId, setStateActiveHouseId] = useState('all');
function handleChangeTheme() {
setStateTheme((oldTheme) => (oldTheme === 'dark' ? 'light' : 'dark'));
}
function handleFilter(houseId) {
setStateActiveHouseId(houseId);
}
const filteredCharacters = useMemo(() => {
return filterByHouse(stateActiveHouseId);
}, [stateActiveHouseId]);
return (
<div className={cn('app', `theme-${stateTheme}`)}>
<Header>
<button className="theme-switch-btn" onClick={handleChangeTheme}>
{stateTheme === 'light' ? 'Nox' : 'Lumos'}
</button>
</Header>
<main className="main">
<Picker activeHouseId={stateActiveHouseId} onChange={handleFilter} />
<p>List starts with {filteredCharacters[0].name}</p>
<OptimizedTable charactersList={filteredCharacters} />
</main>
</div>
);
}
export default App;