[React] Movie-app Notes - Mini Apps (1) To Do List

qeiqiemยท2021๋…„ 11์›” 11์ผ
0

[React] Movie-App

๋ชฉ๋ก ๋ณด๊ธฐ
9/11

๐Ÿ“’ Nomad Coder ReactJS๋กœ ์˜ํ™” ์›น ์„œ๋น„์Šค ๋งŒ๋“ค๊ธฐ
๊ฐ•์˜๋…ธํŠธ (2021 Updated ver.)


# 8. To Do List

state๋Š” ์ ˆ๋Œ€ ์ง์ ‘์ ์œผ๋กœ ์ˆ˜์ •ํ•˜์ง€ ์•Š๋Š”๋‹ค. useState()๋ฅผ ์ด์šฉํ•ด ์ˆ˜์ •ํ•œ๋‹ค.

import React from "react";
import { useState, useEffect } 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 === "") {
            return;
        }
        setToDos((curArry) => [toDo, ...curArry]); // ๋ฐฐ์—ด์— ํ˜„์žฌ state๊ฐ’์„ ์ถ”๊ฐ€ํ•ด์คŒ
        setToDo("");
    };
    console.log(toDos);

    return (
        <div>
            <h1>TO DOS ({toDos.length})</h1>
            <form onSubmit={onSubmit}>
                <input
                    type="text"
                    placeholder="WRITE YOUR TO DO"
                    value={toDo}
                    onChange={onChange}
                ></input>
                <button>add</button>
            </form>
        </div>
    );
}

export default App;

toDos Array์— ์žˆ๋Š” ๋ชจ๋“  ๊ฐ’์„ ๊ฐ๊ฐ ํ•˜๋‚˜์˜ ์ปดํฌ๋„ŒํŠธ๋กœ ์ƒ์„ฑํ•˜๊ธฐ

import React from "react";
import { useState, useEffect } from "react";

function App() {
    const [toDo, setToDo] = useState("");
    const [toDos, setToDos] = useState([]); // ์—ฌ๊ธธ ๋ฐฐ์—ด๋กœ ์ž…๋ ฅํ•˜์ง€ ์•Š๊ณ  ""๋กœ ์ž…๋ ฅํ•ด์„œ map์— ์˜ค๋ฅ˜๊ฐ€ ๋‚จ. ๋ฐฐ์—ด๋กœ ์ธ์‹์„ ๋ชป ํ•ด์„œ..
    const onChange = (e) => setToDo(e.target.value);
    const onSubmit = (e) => {
        e.preventDefault();
        if (toDo === "") {
            return;
        }
        setToDos((curArry) => [toDo, ...curArry]); // ๋ฐฐ์—ด์— ํ˜„์žฌ state๊ฐ’์„ ์ถ”๊ฐ€ํ•ด์คŒ
        setToDo("");
    };
    console.log(toDos);

    return (
        <div>
            <h1>TO DOS ({toDos.length})</h1>
            <form onSubmit={onSubmit}>
                <input
                    type="text"
                    placeholder="WRITE YOUR TO DOs"
                    value={toDo}
                    onChange={onChange}
                ></input>
                <button>add</button>
            </form>
            <hr />
            <ul>
                {toDos.map(
                    (
                        item,
                        index //map์˜ ํ•จ์ˆ˜
                    ) => (
                        <li key={index}>{item}</li> //React์—์„œ list์— key๊ฐ’์„ ์š”๊ตฌํ•จ
                    )
                )}
            </ul>
        </div>
    );
}

export default App;
profile
๊ฒ…๋ถ€ํ•˜์ž

0๊ฐœ์˜ ๋Œ“๊ธ€