분홍분홍 코딩 프로젝트

[React.js] Coin tracker 실습 본문

Javascript

[React.js] Coin tracker 실습

봄나물소녀 2022. 1. 3. 08:40
import React, { useEffect, useState } from "react";
import ReactDOM from "react-dom";

function Convert({ onChangeInputValue, value, usd }) {
  return (
    <div>
      <label htmlFor="usd">USD</label>
      <input
        defaultValue={usd}
        type="number"
        placeholder="You have"
        id="usd"
        onChange={onChangeInputValue}
      ></input>
      <label htmlFor="btc">BTC</label>
      <input
        value={value && usd ? Math.floor(usd / value) : ""}
        type="number"
        placeholder="You can get"
        id="btc"
        disabled={true}
      ></input>
    </div>
  );
}

function Select({ coins, handleSelectChange }) {
  return (
    <select onChange={handleSelectChange}>
      <option value="0">Select The Coin</option>
      {coins.map((coin, index) => {
        return (
          <option key={index} value={coin.quotes.USD.price}>
            {coin.name}({coin.symbol}): $ {coin.quotes.USD.price}USD
          </option>
        );
      })}
    </select>
  );
}

function App() {
  const [loading, setLoading] = useState(true);
  const [coins, setCoins] = useState([]);
  const [value, setValue] = useState("");
  const [usd, setUSD] = useState("");
  useEffect(() => {
    fetch("https://api.coinpaprika.com/v1/tickers")
      .then((response) => response.json())
      .then((json) => {
        setCoins(json);
        setLoading(false);
      });
  }, []);

  const handleSelectChange = (e) => {
    setValue(Math.floor(e.target.value));
    setUSD("");
  };

  function onChangeInputValue(e) {
    setUSD(Number(e.target.value));
  }
  return (
    <div>
      <h1>The Coins! ({coins.length})</h1>
      {loading ? (
        <h2>Loading...</h2>
      ) : (
        <Select coins={coins} handleSelectChange={handleSelectChange} />
      )}
      {value !== 0 ? value : null}
      <Convert
        onChangeInputValue={onChangeInputValue}
        value={value}
        usd={usd}
      />
    </div>
  );
}
ReactDOM.render(<App />, document.getElementById("root"));

 

- Coin list fetch 

- 내가 가진 USD로 구매할 수 있는 만큼의 BTC 확인 가능

 

느낀점

state 끌어올리기로 state값을 최상단 component 에서 관리할 수 있는 react의 장점을 느낀 프로젝트였다.