React
React - learn - Thinking in React
보람-
2023. 12. 6. 17:36
https://react.dev/learn/thinking-in-react
- 메뉴판 만들기 (table)
function ProductTable({ products, filterText, inStockOnly }) {
const rows = [];
let lastCategory = null;
products.forEach((product) => {
if (product.name.toLowerCase().indexOf(filterText.toLowerCase()) === -1)
return;
if (inStockOnly && !product.stocked) return;
if (product.category !== lastCategory) {
rows.push(
<ProductCategoryRow
category={product.category}
key={product.category}
/>
);
}
rows.push(<ProductRow product={product} key={product.name} />);
lastCategory = product.category;
});
return (
<table>
<thead>
<tr>
<th>Name</th>
<th>Price</th>
</tr>
</thead>
<tbody>{rows}</tbody>
</table>
);
}
- 상품 카테고리 영역
function ProductCategoryRow({ category }) {
return (
<tr>
<th colSpan="2" className="category">
{category}
</th>
</tr>
);
}
- 상품 영역
function ProductRow({ product }) {
const name = product.stocked ? (
product.name
) : (
<span style={{ color: "red" }}>{product.name}</span>
);
return (
<tr>
<td>{name}</td>
<td>{product.price}</td>
</tr>
);
}
- 메뉴 검색하는 곳과 테이블(메뉴판)에 state 넣어주기
function FilterableProductTable({ products }) {
const [filterText, setFliterText] = useState("");
const [inStockOnly, setInStockOnly] = useState(false);
return (
<div>
<SearchBar
filterText={filterText}
inStockOnly={inStockOnly}
onFilterTextChange={setFliterText}
onInStockOnlyChange={setInStockOnly}
/>
<ProductTable
products={products}
filterText={filterText}
inStockOnly={inStockOnly}
/>
</div>
);
}
- search 한다면
![]() |
![]() |
- checkbox (파는 상품만 볼수있게 선택한다면)
![]() |
![]() |
function SearchBar({
filterText,
inStockOnly,
onFilterTextChange,
onInStockOnlyChange,
}) {
return (
<form>
<input
type="text"
placeholder="Search..."
value={filterText}
onChange={(e) => onFilterTextChange(e.target.value)}
/>
<label>
<input
type="checkbox"
checked={inStockOnly}
onChange={(e) => onInStockOnlyChange(e.target.checked)}
/>
Only show products in stock
</label>
</form>
);
}
※ input box를 사용할때 e.target.value를 useState를 사용해서 상태를 넣어주는데
- 이때 props에 onChange함수에서 사용할수있게 넘겨주기!
function FilterableProductTable({ products }) {
const [filterText, setFliterText] = useState("");
const [inStockOnly, setInStockOnly] = useState(false);
return (
<div>
<SearchBar
filterText={filterText}
inStockOnly={inStockOnly}
onFilterTextChange={setFliterText}
onInStockOnlyChange={setInStockOnly}
/>
</div>
);
}
function SearchBar({
filterText,
inStockOnly,
onFilterTextChange,
onInStockOnlyChange,
}) {
return (
<form>
<input
type="text"
placeholder="Search..."
value={filterText}
onChange={(e) => onFilterTextChange(e.target.value)}
/>
</form>
);
}