[노마드클론] React3-toDo

JH Cho·2022년 9월 13일
0

노마드

목록 보기
3/5

전개연산자(toDos)

const a = [1,2,3,4];
const b = [5,6];

console.log([a, ...b])
//[[1, 2, 3, 4], 5, 6]

전개연산자는 배열 요소들이 추가되었고 그렇지 않은 것은 배열이 그대로 들어감. (객체도 가능)

결국 이런 식으로 돌아가는 것!

let copy = [...toDos];
    copy.push(toDo); //or unshift
    setToDos(copy);

🧨 toDos 기능구현

코드보기
import { useState } from 'react';

function App() {
  const [toDo, setToDo] = useState('');
  const [toDos, setToDos] = useState([]);
  const onChange = (e) => {
    setToDo(e.target.value);
  };
  const onSubmit = (e) => {
    e.preventDefault();
    if (toDo.trim() === '') {
      return alert('입력하세요');
    }
    setToDos((currentArray) => [toDo, ...currentArray]);
    setToDo('');
  };
  console.log(toDos);
  return (
    <div>
      <h1>My To Dos ({toDos.length})</h1>
      <form onSubmit={onSubmit}>
        <input value={toDo} onChange={onChange} type="text" placeholder="Write your to do" />
        <button>Add To Do</button>
      </form>
      <hr />
      <ul>
        {toDos.map((item, index) => {
          return (
            <li key={index}>
              {item}
              <button
                onClick={() => {
                  setToDos((current) => current.filter((value, valueIndex) => valueIndex !== index));
                }}
              >
                X
              </button>
            </li>
          );
        })}
      </ul>
    </div>
  );
}

export default App;

🧨 삭제기능?

<button onClick={() => {
 setToDos((current) => current.filter((value) =>
                  toDos.indexOf(value) !== index));
 }}>X</button>
//아니면 filter의 두번째 매개변수는 index기 때문에
current.filter((value,valueIndex) =>
                  valueIndex !== index));

또는

let copy = [...toDos];
copy.splice(index, 1);
setTodos(copy);

코인트래커

  1. UI 구성
  2. useEffect로 코인 데이터 최초 1회 불러오기
  3. selector 내의 option은 map 사용해서 구성
  4. input은 컴포넌트로 따로 빼서 구성하기
  5. 일단 BTC 기준으로 함 쫄래쫄래 만들어보자
  6. 그러고 props 이용해서 셀렉터 value에 따라 해당 코인 컨버터로 바꾸기!

🧨 코인 계산기 기능구현

코드보기
import { useEffect, useState } from 'react';

function App() {
  const [loading, setLoading] = useState(true);
  const [coins, setCoins] = useState([]);
  const [index, setIndex] = useState('0');

  useEffect(() => {
    fetch('https://api.coinpaprika.com/v1/tickers')
      .then((response) => response.json())
      .then((json) => {
        setCoins(json);
        setLoading(false);
      });
  }, []);

  const onSelect = (e) => {
    setIndex(e.target.value);
  };

  return (
    <div>
      <h1>The Coins({coins.length})</h1>
      {loading ? <strong>Loading...</strong> : null}
      <select value={index} onChange={onSelect}>
        {coins.map((coin, index) => {
          return (
            <option value={index} key={coin.id}>
              {coin.name}({coin.symbol}) : {coin.quotes['USD']['price']}USD
            </option>
          );
        })}
      </select>
      <UsdToCoin coins={coins} index={index} />
    </div>
  );
}
function UsdToCoin({ coins, index }) {
  const [input, setInput] = useState(0);
  const handleInput = (e) => {
    setInput(e.target.value);
  };
  return (
    <div>
      <input value={input} onChange={handleInput} placeholder="your money"></input>
      <input value={input !== 0 ? (input / coins[index].quotes['USD']['price']).toFixed(3) + coins[index].symbol : 0} placeholder="convert" onChange={handleInput}></input>
    </div>
  );
}

export default App;
profile
주먹구구식은 버리고 Why & How를 고민하며 프로그래밍 하는 개발자가 되자!

0개의 댓글