ReactJS Day7

Jisu Lee·2023년 6월 10일
0

ReactJS 코드 모음집

목록 보기
7/7

오늘은 ReactJS 스터디 일곱 번째 날입니다..새벽 2시반..일찍일찍 강의를 들읍시다..

#7.0~7.1 (To do List)

creating a list of to-dos in the console

import { useState, useEffect } from "react";

function App(){
  const [toDo, setToDo] = useState("");
  const [toDos, setToDos] = useState([]);
  const onChange =(event) => setToDo(event.target.value);
  const onSubmit = (event) => {
    event.preventDefault();
    //if toDo is empty, will kill the function
    //else add toDo and empty the input (will call setToDo again and empty the input as settoDo modifies the toDo value)
    if(toDo===""){
      return;
    }
    //we don't modify the state directly, we always use the modifier function
    setToDo("");
    //we make a function and we receive the current array, then we want to return a new array, the new array will have the toDo + all the previous toDos
    // we do [something you want to add, ...the previous array]
    //will receive the empty arrary [] for the very first time so it will be just toDo, ...[]
    setToDos(currentArray =>[toDo, ...currentArray]);
  };
  console.log(toDos);
  //need to add {} inside <h1></h1> for javascript or javascript will understand it only as a string
  return <div>
    <h1>My To Dos ({toDos.length})</h1>
    <form onSubmit={onSubmit}>
    <input onChange={onChange} value={toDo} type="text" placeholder="Write your to-do"/>
    <button>Add To Do</button>
    </form>
  </div>;
  //button inside the form will submit the form so we will prevent default 
}

export default App;

using map function to display the list

import { useState, useEffect } from "react";

function App(){
  const [toDo, setToDo] = useState("");
  const [toDos, setToDos] = useState([]);
  const onChange =(event) => setToDo(event.target.value);
  const onSubmit = (event) => {
    event.preventDefault();
    if(toDo===""){
      return;
    }
    //(1) if setToDo is called with an empty string, then toDo will be an empty string
    setToDo("");
    //(2) we send a function instead of value
    //will receive the empty arrary [] for the very first time so it will be just toDo, ...[]
    setToDos(currentArray =>[toDo, ...currentArray]);
  };
  return <div>
    <h1>My To Dos ({toDos.length})</h1>
    <form onSubmit={onSubmit}>
    <input onChange={onChange} value={toDo} type="text" placeholder="Write your to-do"/>
    <button>Add To Do</button>
    </form>
    <hr />
    <ul>
    {toDos.map((item, index)=><li key={index}>{item}</li>)}
    </ul>
  </div>;
  //function in map() will be run for every item in the array and return a new array (wiil transform and put in the new array) 
  //first argument of the map function is the value (item) and the second argument is the index, key should be unique 
}

export default App;

#7.2 (Coin Tracker)

extracting json from response and setting the value with the json (coins)

import { useState, useEffect } from "react";

function App(){
  const [loading, setLoading] = useState(true);
  //default values which is empty but not undefined
  const [coins, setCoins] = useState([])
  //will be watching nothing so the code will only run once
  //extract the json from the response of tickers, so we fetch and then get the response and want to return response.json and want to take that json
  //when we get the json which is the coins, we will setCoins to the value of the json  (will have array of coins)
  useEffect(()=>{
    fetch("https://api.coinpaprika.com/v1/tickers").then((respone)=>
    respone.json()
    ).then(json => setCoins(json));
    setLoading(false);
  },[])
  return(
    <div>
    <h1>The Coins! ({coins.length})</h1>
    {loading ? <strong>Loading...</strong> : null}
    <ul>
      {coins.map((coin)=> <li>{coin.name} ({coin.symbol}): ${coin.quotes.USD.price} USD</li>)}
    </ul>
  </div>
  //we don't need the index for the coin as the coin has the id which we can use as the key
  );
}
export default App;

using select and option instead of ul and li

import { useState, useEffect } from "react";

function App(){
  const [loading, setLoading] = useState(true);
  //default values which is empty but not undefined
  const [coins, setCoins] = useState([])
  //will be watching nothing so the code will only run once
  //extract the json from the response of tickers, so we fetch and then get the response and want to return response.json and want to take that json
  //when we get the json which is the coins, we will setCoins to the value of the json  (will have array of coins)
  useEffect(()=>{
    fetch("https://api.coinpaprika.com/v1/tickers").then((respone)=>
    respone.json()
    ).then(json => setCoins(json));
    setLoading(false);
  },[])
  return(
    <div>
    <h1>The Coins! {loading ? "" :`(${coins.length})`}</h1>
    {loading ? <strong>Loading...</strong> : (<select>
      {coins.map((coin)=> <option>{coin.name} ({coin.symbol}): ${coin.quotes.USD.price} USD</option>)}
    </select>)}
  </div>
  //we don't need the index for the coin as the coin has the id which we can use as the key
  );
}
export default App;

the challenge (converting how many coins you can get from investing dollars)

import { useState, useEffect } from "react";

function App() {
  const [loading, setLoading] = useState(true);
  const [coins,setCoins] = useState([]); 
  const [cost,setCost] = useState(1);
  const [need, setNeed] = useState(1);
  const onChange = (event) => {
    setCost(event.target.value);
    setNeed(1);
  }
  const handleInput = (event) => {
    setNeed(event.target.value);
  } 
  useEffect(()=>{
    fetch("https://api.coinpaprika.com/v1/tickers")
      .then((response) => response.json())
      .then((json) => {
        setCoins(json);
        setLoading(false);
      });
  },[]);
  return (
  <div>
    <h1>The coins!{loading ? "" :` Here are..${coins.length} coins`}</h1>
    {loading ? <strong>loading...</strong> : <select onChange={onChange}>
      <option>Select Coin!</option>
      {coins.map((coin , index) =>
      <option 
        key={index} 
        value={coin.quotes.USD.price} 
        id={coin.symbol}
        symbol = {coin.symbol} >
        {coin.name}({coin.symbol}) : ${coin.quotes.USD.price} USD
        </option>
       )}
    </select>}
    <h2>Please enter the amount (in dollars)</h2>
    <div>
      <input type="number" value={need} onChange={handleInput} placeholder="dollars ($)"/>
    </div>
    <h2>You can get {need/cost}</h2>
  </div>);
}
export default App;

0개의 댓글