View

ReatJS 실습(1) - To Do List

  • App.js
import { useState } from "react";

function ToDoList() {
  const [toDo, setToDo] = useState("");
  const [toDos, setToDos] = useState([]);
  const onChange = (event) => setToDo(event.target.value);
  const onSubmit = (event) => {
    event.preventDefault();
    if (toDo === "") {
      return;
    }
    setToDo("");
    setToDos((currentArray) => [toDo, ...currentArray]);
  };
  return (
    <div>
      <h1>To-Do List ({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>
  );
}

export default ToDoList;

 

기존 array의 element들로 새로운 array를 만들고 싶다면? 🤔

const food = [1, 2, 3, 4];

// food 배열에 6을 추가하고 싶다면
[6, food];	//[6, Array(4)] (X)
[6, ...food];	//[6, 1, 2, 3, 4] (O)

 

Map 이란? 🤔

배열의 아이템만큼 새로운 배열을 만들어서 return 해줌

배열을 가지고 있을 때 각각의 element들을 바꿀 수 있게 해줌
map() 은 ()에 함수를 넣을 수 있는데 배열의 모든 item에 대해 실행됨
즉, 배열에 6개의 item이 있다면 6번 함수가 실행됨
그리고 그 함수로부터 내가 return한 값은 새로운 배열에 들어가게 함

[‘a’, ‘b’, ‘c’, ‘d’, ‘e’, ‘f’].map(() => “:)”)	//-> [‘:)’, ‘:)’, ‘:)’, ‘:)’, ‘:)’ ‘:)’]

 


또한 map은 함수의 첫 번째 argument로 현재의 item을 가지고 올 수 있음
map(item) -> item이나 원하는 어떤 변수명을 넣으면 item자체를 리턴하는 것도 가능
map((item) => item.toUpperCase()) : 대문자로 바뀐 item으로 새로운 배열은 만들어줌

리액트는 기본적으로 list에 있는 모든 item을 인식하기 때문에 key를 넣어 고유하게 만들어줘야함
map의 첫 번째 argument는 값이고 두번째는 index 즉 숫자를 의미함

{toDos.map((item, index) => {item})}


즉, {{item},{item},{item}...} 배열을 만들어 각자 고유의 key를 가지게 함

 

주의할 점

state를 변경할 때는 직접적으로 변경할 수 없음. -> useState 함수 사용

toDo = "";	//불가
toDos.push();	//불가

 

To Do List 전체 코드

더보기
import { useState } from "react";

function ToDoList() {
  const [toDo, setToDo] = useState("");
  const [toDos, setToDos] = useState([]);
  const onChange = (event) => setToDo(event.target.value);
  const onSubmit = (event) => {
    event.preventDefault();
    if (toDo === "") {
      return;
    }
    setToDo("");
    setToDos((currentArray) => [toDo, ...currentArray]);
  };
  const onClick = (event) => {
    const todo = event.target.nextSibling;
    if(event.target.checked){
      todo.style.color = "rgba(255, 255, 255, 0.5)";
      todo.style.textDecoration = "line-through rgba(255, 255, 255, 0.8)";
    }else {
      todo.style.color = "#fff";
      todo.style.textDecoration = "none";
    }
  }
  const deleteBtn = index => {
    setToDos((curToDos) => curToDos.filter((_, curIndex) => curIndex !== index));
  }
  return (
    <div className="container">
      <h1 className="header">TO-DO LIST</h1>
      <form className="add-task" onSubmit={onSubmit}>
        <input
          onChange={onChange}
          value={toDo}
          className="task-input"
          type="text"
          placeholder="Write your to do..."
        />
        <button className="addBtn"></button>
      </form>
      <ul>
        {
          toDos.map((item, index) => (
            <li key={index}>
              <input
                onClick={onClick}
                value={index}
                id={index}
                type="checkbox"
              />
              <label htmlFor={index}>{item}</label>
              <button 
                className="deleteBtn"
                onClick={() => deleteBtn(index)}
              >
              </button>
            </li>
          ))
        }
      </ul>
    </div>
  );
}

export default ToDoList;

[css 출처 : https://wsss.tistory.com/1581 ]

 

⚡ TO-DO 삭제 기능

  <button className="deleteBtn" onClick={() => deleteBtn(index)}

 

배열에 항목 제거하기

전달받은 index와 같지 않은 list를 filter한 새 배열로 변경해준다.

// toDos 배열에서 index가 파라미터와 일치하지 않는 원소만 추출해서 새로운 배열을 만들어줌

const deleteBtn = index => {
	setToDos((curToDos) => curToDos.filter((_, curIndex) => curIndex !== index));
}
 curToDos.filter((_, curIndex) => curIndex !== index))​

toDos Map (item,index)에서 두번째 변수만 필요하기 때문에 사용하지 않는 변수는 _로 표기해줌

 

Filter란? 🤔

배열에서 특정 조건이 만족하는 원소들만 추출하여 새로운 배열을 만들어주는 배열 내장 함수

(true면 유지, false면 버림)

 

728x90
Share Link
reply
«   2024/10   »
1 2 3 4 5
6 7 8 9 10 11 12
13 14 15 16 17 18 19
20 21 22 23 24 25 26
27 28 29 30 31