Home [React] 리스트 클릭 시 삭제하기 (filter)
Post
Cancel

[React] 리스트 클릭 시 삭제하기 (filter)


filter 함수를 이용해서 주로 todolist에 많이 쓰이는 버튼 클릭 시 원하는 요소만 삭제되는 기능을 완성해보자!!!

App.js

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
32
33
34
35
36
37
38
39
import { useState } from "react";
import "./App.css";

function App() {
  //리스트 배열
  const [list, setList] = useState([1, 2, 3, 4, 5, 6, 7]);
  //input에 입력하는 text값 관리 state
  const [text, setText] = useState("");

  //input에 값이 바뀔때마다 실행
  const textOnChange = (text) => {
    setText(text.target.value);
  };
  //엔터를 누르거나 +버튼 클릭시 실행
  const onSubmit = (e) => {
    e.preventDefault();
    setList((list) => [...list, text]);
    setText("");
  };

  return (
    <div className="container">
      <form className="textForm" onSubmit={(e) => onSubmit(e)}>
        <input value={text} onChange={(text) => textOnChange(text)} />
        <button type="submit">+</button>
      </form>
      <ul className="list">
        {list.map((data, index) => (
          <li key={data}>
            {data}
            <button>X</button>
          </li>
        ))}
      </ul>
    </div>
  );
}

export default App;

App.css

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
32
33
34
35
36
37
body{
    height:100vh;
    background-color: rgb(37, 37, 37);
}

#root{
    display: flex;
    justify-content: center;
    height: 100%;
}

.container{
    margin-top: 100px;
    width: 300px;
    height: 300px;
    background-color: rgb(255, 255, 255);
}

.textForm>input{
    width:90%;
    outline: none;
}
.textForm>button{
    outline: none;
    cursor: pointer;
}

.list{
    width: 80%;
}
.list>li>button{
    margin-left: 50px;
}
.list>li>button:hover{
    background-color: goldenrod;
    cursor: pointer;
}

위 코드대로라면 아래 사진과 같은 ui가 완성되고
input 창에 text 입력 후 엔터키 or +버튼 클릭을 하면 바로 리스트가 하나 더 추가가 됩니다

image


마우스를 x버튼 위에 올리면 색깔이 변하며 클릭하면 누른 요소만 리스트에서 사라진다

image


추가 코드

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
32
33
34
35
36
37
38
39
40
41
42
import { useState } from "react";
import "./App.css";

function App() {
  //리스트 배열
  const [list, setList] = useState([1, 2, 3, 4, 5, 6, 7]);
  //input에 입력하는 text값 관리 state
  const [text, setText] = useState("");

  //input에 값이 바뀔때마다 실행
  const textOnChange = (text) => {
    setText(text.target.value);
  };
  //엔터를 누르거나 +버튼 클릭시 실행
  const onSubmit = (e) => {
    e.preventDefault();
    setList((list) => [...list,text]);
    setText("");
  };
  //추가코드
  //X버튼 클릭시 해당 요소를 삭제
  const XBtnOnClick = (index) =>{
    const newList = list.filter((value,number)=>number !== index);
    setList(newList)
  };

  return (
    <div className="container">
      <form className="textForm" onSubmit={(e) => onSubmit(e)}>
        <input value={text} onChange={(text) => textOnChange(text)} />
        <button type="submit">+</button>
      </form>
      <ul className="list">
        {list.map((data,index)=>(
          <li key={data}>{data}<button onClick={()=>XBtnOnClick(index)}>X</button></li>
        ))}
      </ul>
    </div>
  );
}

export default App;

위 코드를 추가하고 X버튼을 클릭하면 클릭한 요소만 리스트에서 사라지는걸 볼 수 있습니다.

image


마치며

혹시 잘못된 정보나 궁금하신 게 있다면 편하게 댓글 달아주세요.
지적이나 피드백은 언제나 환영입니다.

This post is licensed under CC BY 4.0 by the author.