Develop/React.js

[React] input 데이터 저장/삭제하기

dawonny 2022. 7. 23. 13:02
728x90
반응형

유저가 입력한 input 데이터를 state 에 저장하고, 삭제하는 기능을 구현해보았다.

 

input 태그에는 여러 type 이 있다. 

필요한 기능을 그때 그때 찾아 쓰면 되겠다.

<input type="text"/>
<input type="range"/>
<input type="date"/>
<input type="number"/>
<textarea></textarea>
<select></select>

 

이 input 태그에 뭔가 키보드로 글자를 입력할때 코드를 실행하려면 onChange 를 쓴다.

이벤트 핸들러라고 한다.

onMouseOver={ }

onScroll={ } 등..

 

이 input에 입력한 값을 가져오려면 e.target.value 를 쓴다.

e는 이벤트 객체다.

 

e.preventDefault()  는 이벤트 기본동작을 막고

e.stopPropagation() 은 이벤트 버블링을 막는다.(버튼 하나 눌렀는데 다른 onClick 까지 실행 되어버리는 버그)

 

이를 이용해서 저장/삭제 기능을 구현해봤다.

/*eslint-disable*/
import logo from "./logo.svg";
import "./App.css";
import { useState } from "react";

function App() {
  let [title, setTitle] = useState([
    "남자 코트 추천",
    "강남 우동맛집",
    "파이썬 독학",
  ]);
...
  let [input, setInput] = useState("");

...

  function deleteTitle(i) {
    let copy = [...title];
    copy.splice(i, 1);
    setTitle(copy);
  }

...

  return (
    <div className="App">
      <div className="black-nav">
        <h4>ReactBlog</h4>
      </div>
...

      {title.map(function (a, i) {
        return (
          <div className="list" key={i}>
            <h4
              onClick={() => {
                setDetailTitle(i);
                setModal(!modal);
              }}
            >
              {title[i]}{" "}
              <span
                onClick={(e) => {
                  e.stopPropagation();
                  addLike(i);
                }}
              >
                👍
              </span>{" "}
              {like[i]}
            </h4>
            <p>2022-07-15</p>
            <button onClick={() => deleteTitle(i)}> DELETE</button>
          </div>
        );
      })}

      <input
        onChange={(e) => {
          setInput(e.target.value);
          console.log(input);
        }}
      ></input>
      <button onClick={() => setTitle([...title, input])}>SAVE</button>
      {modal == true ? (
        <Modal detailTitle={detailTitle} color={"skyblue"} title={title} />
      ) : null}
    </div>
  );
}

function Modal(props) {
...
}

export default App;

두 가지 방법을 다 써봤다.

저장할때에는 따로 함수를 만들지 않고 setTitle 함수를 써서 input 데이터를 title 리스트 state 의 맨 뒤에 추가하는 방식으로 했고

 

삭제할 때에는 deleteTitle 함수를 따로 만들어서 index를 알면 index 에 해당하는 위치로부터 title 의 항목을 하나 지우도록 했다.

 

* 원래 삭제 기능 만들때에도 바로 setTitle 함수를 썼었는데 이렇게 구현하니까 1개가 아닌 2개가 지워져버리는 문제가 있었다. 구글링 해보니까 이 작성자와 비슷한 문제가 아닐까 싶다.

https://stackoverflow.com/questions/64266062/react-splice-removing-too-many-elements-from-state-array

 

React - Splice removing too many elements from state array

I'm trying to create an image gallery that has a variable number of inputs. I have successfully created an add button which will add a new element to my array that is in the state. However, when I ...

stackoverflow.com

 

결과화면

728x90
반응형