kohigowild
React :: COIN TRACKER 본문
텍스트 상자에 가지고 있는 시드 머니를 입력한 뒤 옵션을 선택하면, 선택한 코인을 얼마나 구매할 수 있는지 출력해 주는 간단한 프로그램이다.
const [loading, setLoading] = useState(true);
const [coins, setCoins] = useState([]);
useEffect(() => {
fetch("https://api.coinpaprika.com/v1/tickers")
.then((response) => response.json())
.then((json) => {
setCoins(json.slice(0, 100));
setLoading(false);
});
}, []);
- api 로딩 시 state 값은 true, 로딩이 끝나면 false
- 코인 정보를 담을 배열을 만들고, fetch()를 통해 코인 api를 불러온다. 응답이 완료된 이후 loading state는 false로 바뀐다. => setLoading(false)
- 옵션창이 너무 길어져서 100개까지만 출력할 수 있도록 설정하였다.
const [seed, setSeed] = useState(0);
const [getCoin, setGetCoin] = useState(0);
const [name, setName] = useState("");
const onChange = (e) => {
setSeed(e.target.value);
};
const onSelect = (e) => {
setGetCoin(coins[e.target.selectedIndex].quotes.USD.price);
setName(coins[e.target.selectedIndex].name);
};
- input에 넣을 onChange 이벤트와 select에 넣을 onSelect 이벤트 => input 값을 변경하면 setSeed를 통해 seed 갱신, 마찬가지로 옵션 선택 시 setGetCoin을 통해 getCoin에는 코인의 가격이 저장되고, setName을 통해 name에 코인의 이름이 저장된다.
return (
<div>
<h1>The Coins! {loading ? "" : `(${coins.length})`}</h1>
{loading ? (
<strong>Loading...</strong>
) : (
<>
<h3>WRITE YOUR SEED MONEY</h3>
<input type="number" value={seed} onChange={onChange}></input> USD
<div>
<h3>SELECT COIN!</h3>
<select onChange={onSelect}>
{coins.map((coin, index) => (
<option key={index}>
{coin.name} ({coin.symbol}): ${coin.quotes.USD.price.toFixed(2)} USD
</option>
))}
</select>
<div>
{seed === "" ? null : (
<h3>
YOU CAN BUY {getCoin > 0 ? (seed / getCoin).toFixed(2) : null} AMOUNT OF {name}
</h3>
)}
</div>
</div>
</>
)}
</div>
);
- 타이틀 옆 괄호 안에는 코인 옵션의 개수가 출력되고, 로딩 중에는 아무것도 출력되지 않는다.
- 로딩 시 (loading state가 true일 때) <strong>Loading...</strong> 출력
- 응답이 완료된 이후 (loading state가 false) COIN TRACKER 출력
전체 코드
import { useState, useEffect } from "react";
function App() {
const [loading, setLoading] = useState(true);
const [coins, setCoins] = useState([]);
const [seed, setSeed] = useState(0);
const [getCoin, setGetCoin] = useState(0);
const [name, setName] = useState("");
useEffect(() => {
fetch("https://api.coinpaprika.com/v1/tickers")
.then((response) => response.json())
.then((json) => {
setCoins(json.slice(0, 100));
setLoading(false);
});
}, []);
const onChange = (e) => {
setSeed(e.target.value);
};
const onSelect = (e) => {
setGetCoin(coins[e.target.selectedIndex].quotes.USD.price);
setName(coins[e.target.selectedIndex].name);
};
return (
<div>
<h1>The Coins! {loading ? "" : `(${coins.length})`}</h1>
{loading ? (
<strong>Loading...</strong>
) : (
<>
<h3>WRITE YOUR SEED MONEY</h3>
<input type="number" value={seed} onChange={onChange}></input> USD
<div>
<h3>SELECT COIN!</h3>
<select onChange={onSelect}>
{coins.map((coin, index) => (
<option key={index}>
{coin.name} ({coin.symbol}): ${coin.quotes.USD.price.toFixed(2)} USD
</option>
))}
</select>
<div>
{seed === "" ? null : (
<h3>
YOU CAN BUY {getCoin > 0 ? (seed / getCoin).toFixed(2) : null} AMOUNT OF {name}
</h3>
)}
</div>
</div>
</>
)}
</div>
);
}
export default App;
Reference
'React' 카테고리의 다른 글
[React] props와 state (0) | 2022.12.15 |
---|---|
REACT 컴포넌트 생명 주기 (Life Cycle) (0) | 2022.12.10 |
React로 간단한 To-Do-List 구현 (0) | 2022.11.24 |
React useState(), useEffect() (0) | 2022.11.15 |
React JSX 문법과 예제 정리 (0) | 2022.11.09 |