• 브라우저에 저장하려면 localStorage 필요
  •  localStorage는 오직 텍스트만 저장 가능
  • JSON.stringify : 오브젝트이든 배열이든 string으로 만들어줌  
const toDoForm = document.getElementById("todo-form");
const toDoInput = toDoForm.querySelector("input"); //document.querySelector("#todo-form input");
const toDoList = document.getElementById("todo-list");

const toDos = [];

function saveToDos(){
    localStorage.setItem("todos",JSON.stringify(toDos)); //배열을 문자열로 만들어줌
}

function deleteToDo(event){
    const li = event.target.parentElement;//target:클릭된 html element(button), parentElement-Element의 부모
    li.remove();
}

function paintToDo(newTodo){
    const li = document.createElement("li");
    const span = document.createElement("span");
    const button = document.createElement("button");
    button.innerText = "❌";
    button.addEventListener("click",deleteToDo); //button을 클릭하면 event를 얻음
    li.appendChild(span);
    li.appendChild(button); //button은 span뒤에 있어야 함
    span.innerText = newTodo;
    toDoList.appendChild(li);
}

function toDoSubmit(event){
    event.preventDefault();
    const newTodo = toDoInput.value;
    toDoInput.value = "";
    toDos.push(newTodo);
    paintToDo(newTodo);
    saveToDos(); 
}

toDoForm.addEventListener("submit",toDoSubmit);

'JavaScript' 카테고리의 다른 글

#7.5 Loading To Dos part Two  (2) 2023.02.15
#7.4 Loading To Dos part One  (1) 2023.02.15
#7.2 Deleting To Dos  (2) 2023.02.15
#7.1 Adding ToDos  (2) 2023.02.15
#7.0 Setup  (1) 2023.02.15
function deleteToDo(event){
    const li = event.target.parentElement;//target:클릭된 html element(button), parentElement-Element의 부모
    li.remove();
}

function paintToDo(newTodo){
    const li = document.createElement("li");
    const span = document.createElement("span");
    const button = document.createElement("button");
    button.innerText = "❌";
    button.addEventListener("click",deleteToDo); //button을 클릭하면 event를 얻음
    li.appendChild(span);
    li.appendChild(button); //button은 span뒤에 있어야 함
    span.innerText = newTodo;
    toDoList.appendChild(li);
}

'JavaScript' 카테고리의 다른 글

#7.4 Loading To Dos part One  (1) 2023.02.15
#7.3 Saving To Dos  (4) 2023.02.15
#7.1 Adding ToDos  (2) 2023.02.15
#7.0 Setup  (1) 2023.02.15
#6.1 Background  (0) 2023.02.13
<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <link rel="stylesheet" href="css/style.css">
    <title>Hello from HTML!</title>
</head>

<body>
    <form id="login-form" class="hidden">
        <input required maxlength="15" type="text" placeholder="What is your name?" />
        <button>Log In</button>
    </form>
    <h2 id="clock">00:00:00</h2>
    <h1 id="greeting" class="hidden"></h1>
    <form id="todo-form">
        <input type="text" placeholder="Write a To Do and Press Enter" required/>
    </form>
    <ul id="todo-list"></ul>
    <div id="quote">
        <span></span>
        <span></span>
    </div>
    <script src="js/clock.js"></script>
    <script src="js/greetings.js"></script>
    <script src="js/quotes.js"></script>
    <script src="js/background.js"></script>
    <script src="js/todo.js"></script>
</body>

</html>​
const toDoForm = document.getElementById("todo-form");
const toDoInput = toDoForm.querySelector("input"); //document.querySelector("#todo-form input");
const toDoList = document.getElementById("todo-list");

function paintToDo(newTodo){
    const li = document.createElement("li");
    const span = document.createElement("span");
    li.appendChild(span);
    span.innerText = newTodo;
    toDoList.appendChild(li);
}

function toDoSubmit(event){
    event.preventDefault();
    const newTodo = toDoInput.value;
    toDoInput.value = "";
    paintToDo(newTodo);
}

toDoForm.addEventListener("submit",toDoSubmit);

'JavaScript' 카테고리의 다른 글

#7.3 Saving To Dos  (4) 2023.02.15
#7.2 Deleting To Dos  (2) 2023.02.15
#7.0 Setup  (1) 2023.02.15
#6.1 Background  (0) 2023.02.13
#6.0 Quotes  (1) 2023.02.13
<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <link rel="stylesheet" href="css/style.css">
    <title>Hello from HTML!</title>
</head>

<body>
    <form id="login-form" class="hidden">
        <input required maxlength="15" type="text" placeholder="What is your name?" />
        <button>Log In</button>
    </form>
    <h2 id="clock">00:00:00</h2>
    <h1 id="greeting" class="hidden"></h1>
    <form id="todo-form">
        <input type="text" placeholder="Write a To Do and Press Enter" required/>
    </form>
    <ul id="todo-list"></ul>
    <div id="quote">
        <span></span>
        <span></span>
    </div>
    <script src="js/clock.js"></script>
    <script src="js/greetings.js"></script>
    <script src="js/quotes.js"></script>
    <script src="js/background.js"></script>
    <script src="js/todo.js"></script>
</body>

</html>​
const toDoForm = document.getElementById("todo-form");
const toDoInput = toDoForm.querySelector("input"); //document.querySelector("#todo-form input");
const toDoList = document.getElementById("todo-list");

function toDoSubmit(event){
    event.preventDefault();
    const newTodo = toDoInput.value;
    toDoInput.value = "";
}

toDoForm.addEventListener("submit",toDoSubmit);

'JavaScript' 카테고리의 다른 글

#7.2 Deleting To Dos  (2) 2023.02.15
#7.1 Adding ToDos  (2) 2023.02.15
#6.1 Background  (0) 2023.02.13
#6.0 Quotes  (1) 2023.02.13
#5.2 PadStart  (0) 2023.02.10
import React from "react";
import {
    BrowserRouter,
    Routes,
    Route,
    Link,
    useNavigate,
} from "react-router-dom";
export default function BasicExample() {
    return (
        <BrowserRouter>
            <button>
                <Link to="/home">Home</Link>
            </button>
            <button>
                <Link to="/">Index</Link>
            </button>
            <Routes> //경로가 바뀌면 Routes컴포넌트는 하위에 있는 Route컴포넌트들 중에 하나를 찾음
                <Route exact path="/" element={<Index />} /> //찾는 기준은 path가 정확하게 일치하는지를 기준으로
                <Route path="/home" element={<Home />} /> //경로가 /home이면 element어트리뷰트에 들어있는 <Home />이라는 컴포넌트가 리턴돼서 home이 렌더링 됨
            </Routes>
        </BrowserRouter>
    );
}
function Index() {
    let navigate = useNavigate(); //useNavigate를 사용하면 navigate라는 객체가 나오고 
    function handleClick() { // 이게 클릭이 되면
        navigate("/home"); //navigate객체에 /home경로전달->리액트에서 나타나는 현재 경로를 바꿔줄 수 있음, navigate는 입력받은 경로로 이동함
    }
    return (
        <>
            <h2>Index</h2>
            <button type="button" onClick={handleClick}>
                Go home
            </button>
        </>
    );
}
function Home() {
    return (
        <>
            <h2>Home</h2>
            <p>This is home</p>
        </>
    );
}

'React' 카테고리의 다른 글

리액트16강  (0) 2023.02.16
리액트 15강  (3) 2023.02.15
리액트 13강  (2) 2023.02.13
리액트 12강  (3) 2023.02.12
리액트 11강  (1) 2023.02.11
const images = ["0.jpg","1.jpg","2.jpg"]; //폴더 안에 있는 이미지 이름이랑 똑같게

const chosenImage = images[Math.floor(Math.random()*images.length)];

const bgImage = document.createElement("img"); //img요소 생성

bgImage.src = `img/${chosenImage}`;

document.body.appendChild(bgImage) //body에 html추가(가장 뒤에)

'JavaScript' 카테고리의 다른 글

#7.1 Adding ToDos  (2) 2023.02.15
#7.0 Setup  (1) 2023.02.15
#6.0 Quotes  (1) 2023.02.13
#5.2 PadStart  (0) 2023.02.10
#5.1 Timeouts and Dates  (0) 2023.02.10
  • 랜덤 명언 불러오기
const quotes = [{
    quote:"하루에 3시간을 걸으면 7년 후에 지구를 한바퀴 돌 수 있다",
    author:"사무엘존슨"
},{
    quote:"삶이 있는 한 희망은 있다",
    author:"키케로"
},{
    quote:"언제나 현재에 집중할수 있다면 행복할것이다.",
    author:"파울로 코엘료"
},{
    quote:"행복의 문이 하나 닫히면 다른 문이 열린다 그러나 우리는 종종 닫힌 문을 멍하니 바라보다가 우리를 향해 열린 문을 보지 못하게 된다",
    author:"헬렌켈러"
},{
    quote:"먼저 자신을 비웃어라. 다른 사람이 당신을 비웃기 전에",
    author:"엘사 맥스웰"
},{
    quote:"절대 어제를 후회하지 마라. 인생은 오늘의 나 안에 있고 내일은 스스로 만드는 것이다",
    author:"L.론허바드"
},{
    quote:"너무 소심하고 까다롭게 자신의 행동을 고민하지 말라 . 모든 인생은 실험이다 . 더많이 실험할수록 더나아진다",
    author:"랄프 왈도 에머슨"
},{
    quote:"한번의 실패와 영원한 실패를 혼동하지 마라",
    author:"F.스콧 핏제랄드"
},{
    quote:"1퍼센트의 가능성, 그것이 나의 길이다.",
    author:"나폴레옹"
},{
    quote:"고통이 남기고 간 뒤를 보라! 고난이 지나면 반드시 기쁨이 스며든다.",
    author:"괴테"
}
]

const quote = document.querySelector("#quote span:first-child");
const author = document.querySelector("#quote span:last-child");

const todaysQuote = quotes[Math.floor(Math.random()*quotes.length)]; //0에서 1사이의 숫자 * 배열의 길이 -> 정수내림

quote.innerText = todaysQuote.quote;
author.innerText = todaysQuote.author;
<div id="quote">
        <span></span>
        <span></span>
    </div>

'JavaScript' 카테고리의 다른 글

#7.0 Setup  (1) 2023.02.15
#6.1 Background  (0) 2023.02.13
#5.2 PadStart  (0) 2023.02.10
#5.1 Timeouts and Dates  (0) 2023.02.10
#5.0 Intervals  (2) 2023.02.10
  • useEffect
    • 우리가 호출을 하는 훅이 아닌 자동으로 호출이 되는 훅
    • 컴포넌트가 마운트가 되고 dom이 변경 된 다음 렌더링 발생 후 실행됨
    • 언제 필요하냐?
      • props 에 속한 값을 컴포넌트의 로컬 변수로 선언
      • API 호출하여 통신을 통해 값을 받아오거나 받은 값을 state에 값을 넣어주나 할 때 사용 
      • 서드파티 라이브러리 사용
    • 즉, 렌더링이 다 되면 화면에 요소들이 나타나고 그 다음 다시 한번 데이터를 변경할 때 사용하는 것
    • 아래 코드에서 제목이 알아서 바뀐다는 것이 핵심 -> 제목은 useeffect에서 바뀌는것
import React, { useState, useEffect } from "react";

function App() {
    const [count, setCount] = useState(0);

    useEffect(
        () => {
            console.log("use effect");
            document.title = `You clicked ${count} times`; //얘도 실행됨
        }
    )

    return (
        <>
            <p>you clicked {count} times</p>
            <button onClick={
                () => {
                    console.log("Click");
                    setCount(count + 1);
                } //이 부분이 바뀌고 리렌더링 될 때마다
            }
            >
                click me
            </button>
        </>
    )
}

export default App;

'React' 카테고리의 다른 글

리액트 15강  (3) 2023.02.15
리액트 14강  (0) 2023.02.14
리액트 12강  (3) 2023.02.12
리액트 11강  (1) 2023.02.11
리액트 10강  (1) 2023.02.10

+ Recent posts